package com.ssy.lingxi.member.merchant.serviceimpl.web;

import com.querydsl.core.types.Projections;
import com.querydsl.jpa.impl.JPAQuery;
import com.querydsl.jpa.impl.JPAQueryFactory;
import com.ssy.lingxi.common.constant.basic.EnableDisableStatus;
import com.ssy.lingxi.common.constant.manage.ShopTypeEnum;
import com.ssy.lingxi.common.constant.member.*;
import com.ssy.lingxi.common.model.dto.UserLoginCacheDTO;
import com.ssy.lingxi.common.model.vo.SelectItemVO;
import com.ssy.lingxi.common.response.PageData;
import com.ssy.lingxi.common.response.Wrapper;
import com.ssy.lingxi.common.utils.CollectionPageUtil;
import com.ssy.lingxi.common.utils.DateTimeUtil;
import com.ssy.lingxi.member.merchant.api.constant.MemberRelationTypeEnum;
import com.ssy.lingxi.member.merchant.api.constant.MemberRightTypeEnum;
import com.ssy.lingxi.member.merchant.api.model.vo.inner.response.MemberManageQueryVO;
import com.ssy.lingxi.member.merchant.entity.*;
import com.ssy.lingxi.member.merchant.model.constant.MemberManageOrderTypeEnum;
import com.ssy.lingxi.member.merchant.model.constant.MemberStringEnum;
import com.ssy.lingxi.member.merchant.model.constant.MemberValidateStatusEnum;
import com.ssy.lingxi.member.merchant.model.vo.basic.request.MemberNameVO;
import com.ssy.lingxi.member.merchant.model.vo.basic.request.SubMemberIdRoleIdVO;
import com.ssy.lingxi.member.merchant.model.vo.basic.request.UserPageVO;
import com.ssy.lingxi.member.merchant.model.vo.basic.response.*;
import com.ssy.lingxi.member.merchant.model.vo.manage.request.*;
import com.ssy.lingxi.member.merchant.model.vo.manage.response.*;
import com.ssy.lingxi.member.merchant.repository.*;
import com.ssy.lingxi.member.merchant.service.base.*;
import com.ssy.lingxi.member.merchant.service.feign.IPlatformManageFeignService;
import com.ssy.lingxi.member.merchant.service.web.IMemberManageService;
import com.ssy.lingxi.member.merchant.utils.NumberUtil;
import com.ssy.lingxi.platform.manage.api.model.dto.site.SiteIdDTO;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.persistence.criteria.Expression;
import javax.persistence.criteria.Join;
import javax.persistence.criteria.JoinType;
import javax.persistence.criteria.Predicate;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 用户管理接口实现类
 *
 * @author 万宁
 * @version 2.0.0
 * @date 2020-06-03
 */
@Service
public class MemberManageServiceImpl implements IMemberManageService {
    @Resource
    private MemberTypeRepository memberTypeRepository;

    @Resource
    private RoleRepository roleRepository;

    @Resource
    private MemberRelationRepository relationRepository;

    @Resource
    private IBaseMemberCacheService memberCacheService;

    @Resource
    private BaseLevelConfigRepository baseLevelConfigRepository;

    @Resource
    private IBaseUserDetailService baseUserDetailService;

    @Resource
    private MemberLevelConfigRepository memberLevelConfigRepository;

    @Resource
    private IBaseMemberValidateService baseMemberValidateService;

    @Resource
    private IPlatformManageFeignService platformManageFeignService;

    @Resource
    private IBaseMemberLevelConfigService baseMemberLevelConfigService;

    @Resource
    private IBaseSiteService siteService;

    @Resource
    private JPAQueryFactory jpaQueryFactory;

    /**
     * 商城类型 - 企业商城 - 1
     */
    private final Integer MALL_TYPE_ENTERPRISE = 1;

    /**
     * 商城类型 - 积分商城 - 2
     */
    private final Integer MALL_TYPE_SCORE = 2;

    /**
     * 商城类型 - 渠道商城 - 3
     */
    private final Integer MALL_TYPE_CHANNEL = 3;

    /**
     * 商城类型 - 渠道自有商城 - 4
     */
    private final Integer MALL_TYPE_CHANNEL_PRIVATE = 4;

    /**
     * 商城类型 - 渠道积分商城 - 5
     */
    private final Integer MALL_TYPE_CHANNEL_SCORE = 5;

    /**
     * 查询所有角色
     * @param headers    Http头部信息
     * @param roleTypeVO 接口参数
     * @return 角色列表
     */
    @Override
    public Wrapper<List<RoleIdAndNameVO>> allRoles(HttpHeaders headers, MemberManageRoleTypeVO roleTypeVO) {
        List<RoleDO> roleDOList = roleRepository.findAll().stream().filter(roleDO -> !roleDO.getRelType().equals(MemberRelationTypeEnum.PLATFORM.getCode())).collect(Collectors.toList());
        if (roleTypeVO.getRoleTypeEnum() != null && !roleTypeVO.getRoleTypeEnum().equals(0)) {
            roleDOList = roleDOList.stream().filter(roleDO -> roleDO.getRoleType().getTypeEnum().equals(roleTypeVO.getRoleTypeEnum())).collect(Collectors.toList());
        }
        return Wrapper.success(roleDOList.stream().map(roleDO -> new RoleIdAndNameVO(roleDO.getId(), roleDO.getRoleName())).sorted(Comparator.comparingLong(RoleIdAndNameVO::getRoleId)).collect(Collectors.toList()));
    }

    /**
     * 查询所有下级渠道会员角色，返回Id和角色名称列表
     * @return 操作结果
     */
    @Override
    public Wrapper<List<RoleIdAndNameVO>> listRoles(HttpHeaders headers) {
        UserLoginCacheDTO loginUser = memberCacheService.checkUserFromCache(headers);
        List<MemberRelationDO> relationDOList = relationRepository.findByMemberIdAndRoleId(loginUser.getMemberId(), loginUser.getMemberRoleId());
        List<RoleIdAndNameVO> roleIdAndNameVOList = relationDOList.stream().filter(relationDO -> relationDO.getStatus().equals(MemberStatusEnum.NORMAL.getCode()) && (relationDO.getSubMemberTypeEnum().equals(MemberTypeEnum.CHANNEL.getCode()) || relationDO.getSubMemberTypeEnum().equals(MemberTypeEnum.CHANNEL_PERSONAL.getCode())))
                .map(relationDO -> new RoleIdAndNameVO(relationDO.getSubRoleId(), relationDO.getSubRoleName()))
                .collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(RoleIdAndNameVO::getRoleId))), ArrayList::new))
                .stream().sorted(Comparator.comparing(RoleIdAndNameVO::getRoleId)).collect(Collectors.toList());
        return Wrapper.success(roleIdAndNameVOList);
    }

    /**
     * 模糊分页查询下级会员列表
     *
     * @param headers HttpHeaders信息
     * @param pageVO  接口参数
     * @return 操作结果
     */
    @Override
    public Wrapper<PageData<MemberManageQueryVO>> pageLowerMembersByName(HttpHeaders headers, MemberManagePageByNameVO pageVO) {
        UserLoginCacheDTO loginUser = memberCacheService.checkUserFromCache(headers);

        Specification<MemberRelationDO> specification = (root, query, criteriaBuilder) -> {
            List<Predicate> list = new ArrayList<>();
            list.add(criteriaBuilder.equal(root.get("memberId").as(Long.class), loginUser.getMemberId()));
            list.add(criteriaBuilder.equal(root.get("roleId").as(Long.class), loginUser.getMemberRoleId()));
            list.add(criteriaBuilder.equal(root.get("verified").as(Integer.class), MemberValidateStatusEnum.VERIFY_PASSED.getCode()));
            list.add(criteriaBuilder.equal(root.get("status").as(Integer.class), MemberStatusEnum.NORMAL.getCode()));

            if (StringUtils.hasLength(pageVO.getName())) {
                Join<Object, Object> subMemberJoin = root.join("subMember", JoinType.LEFT);
                list.add(criteriaBuilder.like(subMemberJoin.get("name").as(String.class), "%" + pageVO.getName().trim() + "%"));
            }

            Predicate[] p = new Predicate[list.size()];
            return criteriaBuilder.and(list.toArray(p));
        };

        Pageable page = PageRequest.of(pageVO.getCurrent() - 1, pageVO.getPageSize(), Sort.by("id").ascending());
        Page<MemberRelationDO> result = relationRepository.findAll(specification, page);
        return Wrapper.success(new PageData<>(result.getTotalElements(), result.getContent().stream().map(relationDO -> {
            MemberManageQueryVO queryVO = new MemberManageQueryVO();
            queryVO.setId(relationDO.getId());
            queryVO.setMemberId(relationDO.getSubMemberId());
            queryVO.setName(relationDO.getSubMember().getName());
            queryVO.setRoleId(relationDO.getSubRoleId());
            queryVO.setRoleName(relationDO.getSubRoleName());
            queryVO.setMemberTypeName(MemberTypeEnum.getCodeMessage(relationDO.getSubRole().getMemberType().getTypeEnum()));
            queryVO.setLevel(relationDO.getLevelRight().getLevel());
            queryVO.setLevelTag(relationDO.getLevelRight().getLevelTag());
            return queryVO;
        }).collect(Collectors.toList())));
    }

    /**
     * 根据下级会员名称、下级会员角色Id，模糊分页查询下级会员列表
     *
     * @param headers HttpHeaders信息
     * @param pageVO  接口参数
     * @return 操作结果
     */
    @Override
    public Wrapper<PageData<MemberManageQueryVO>> pageLowerMembersByNameAndRole(HttpHeaders headers, MemberManagePageByNameAndRoleIdVO pageVO) {
        UserLoginCacheDTO loginUser = memberCacheService.checkUserFromCache(headers);

        Specification<MemberRelationDO> specification = (root, query, criteriaBuilder) -> {
            List<Predicate> list = new ArrayList<>();

            list.add(criteriaBuilder.equal(root.get("memberId").as(Long.class), loginUser.getMemberId()));
            list.add(criteriaBuilder.equal(root.get("roleId").as(Long.class), loginUser.getMemberRoleId()));
            list.add(criteriaBuilder.equal(root.get("verified").as(Integer.class), MemberValidateStatusEnum.VERIFY_PASSED.getCode()));
            list.add(criteriaBuilder.equal(root.get("status").as(Integer.class), MemberStatusEnum.NORMAL.getCode()));
            if (StringUtils.hasLength(pageVO.getName())) {
                Join<Object, Object> subMemberJoin = root.join("subMember", JoinType.LEFT);
                list.add(criteriaBuilder.like(subMemberJoin.get("name").as(String.class), "%" + pageVO.getName().trim() + "%"));
            }

            if (pageVO.getRoleId() != null && pageVO.getRoleId() > 0) {
                list.add(criteriaBuilder.equal(root.get("subRoleId").as(Long.class), pageVO.getRoleId()));
            }

            Predicate[] p = new Predicate[list.size()];
            return criteriaBuilder.and(list.toArray(p));
        };

        Pageable page = PageRequest.of(pageVO.getCurrent() - 1, pageVO.getPageSize(), Sort.by("id").ascending());
        Page<MemberRelationDO> result = relationRepository.findAll(specification, page);

        return Wrapper.success(new PageData<>(result.getTotalElements(), result.getContent().stream().map(relationDO -> {
            MemberManageQueryVO queryVO = new MemberManageQueryVO();
            queryVO.setId(relationDO.getId());
            queryVO.setMemberId(relationDO.getSubMemberId());
            queryVO.setName(relationDO.getSubMember().getName());
            queryVO.setRoleId(relationDO.getSubRoleId());
            queryVO.setRoleName(relationDO.getSubRoleName());
            queryVO.setMemberTypeName(MemberTypeEnum.getCodeMessage(relationDO.getSubRole().getMemberType().getTypeEnum()));
            queryVO.setLevel(relationDO.getLevelRight().getLevel());
            queryVO.setLevelTag(relationDO.getLevelRight().getLevelTag());
            return queryVO;
        }).collect(Collectors.toList())));
    }

    /**
     * 查询上级渠道会员（包括渠道企业、渠道个人）列表，返回会员Id和名称
     *
     * @param headers HttpHeaders信息
     * @return 操作结果
     */
    @Override
    public Wrapper<List<MemberIdAndNameVO>> listUpperChannelMembers(HttpHeaders headers) {
        UserLoginCacheDTO loginUser = memberCacheService.needLoginFromBusinessPlatform(headers);
        Specification<MemberRelationDO> specification = (root, query, criteriaBuilder) -> {
            List<Predicate> list = new ArrayList<>();
            list.add(criteriaBuilder.equal(root.get("subMemberId").as(Long.class), loginUser.getMemberId()));
            list.add(criteriaBuilder.equal(root.get("subRoleId").as(Long.class), loginUser.getMemberRoleId()));
            list.add(criteriaBuilder.equal(root.get("verified").as(Integer.class), MemberValidateStatusEnum.VERIFY_PASSED.getCode()));
            list.add(criteriaBuilder.equal(root.get("status").as(Integer.class), MemberStatusEnum.NORMAL.getCode()));
            Join<Object, Object> roleJoin = root.join("role", JoinType.LEFT);
            list.add(criteriaBuilder.or(criteriaBuilder.equal(roleJoin.get("memberType").get("typeEnum").as(Integer.class), MemberTypeEnum.CHANNEL.getCode()), criteriaBuilder.equal(roleJoin.get("memberType").get("typeEnum").as(Integer.class), MemberTypeEnum.CHANNEL_PERSONAL.getCode())));

            Predicate[] p = new Predicate[list.size()];
            return criteriaBuilder.and(list.toArray(p));
        };

        return Wrapper.success(relationRepository.findAll(specification, Sort.by("id").ascending()).stream().map(r -> {
            MemberIdAndNameVO resultVO = new MemberIdAndNameVO();
            resultVO.setMemberId(r.getMemberId());
            resultVO.setName(r.getMember().getName());
            return resultVO;
        }).collect(Collectors.toList()));
    }

    /**
     * 查询所有“下级渠道会员”的角色，返回Id和角色名称列表
     *
     * @param headers HttpHeaders信息
     * @return 操作结果
     */
    @Override
    public Wrapper<List<RoleIdAndNameVO>> listLowerChannelRoles(HttpHeaders headers) {
        UserLoginCacheDTO loginUser = memberCacheService.checkUserFromCache(headers);
        Specification<MemberRelationDO> specification = (root, query, criteriaBuilder) -> {
            List<Predicate> list = new ArrayList<>();
            list.add(criteriaBuilder.equal(root.get("memberId").as(Long.class), loginUser.getMemberId()));
            list.add(criteriaBuilder.equal(root.get("roleId").as(Long.class), loginUser.getMemberRoleId()));

            Join<Object, Object> subRoleJoin = root.join("subRole", JoinType.LEFT);
            list.add(criteriaBuilder.or(criteriaBuilder.equal(subRoleJoin.get("memberType").get("typeEnum").as(Integer.class), MemberTypeEnum.CHANNEL.getCode()), criteriaBuilder.equal(subRoleJoin.get("memberType").get("typeEnum").as(Integer.class), MemberTypeEnum.CHANNEL_PERSONAL.getCode())));

            Predicate[] p = new Predicate[list.size()];
            return criteriaBuilder.and(list.toArray(p));
        };

        List<RoleIdAndNameVO> queryVOList = relationRepository.findAll(specification).stream().map(relationDO -> {
            RoleIdAndNameVO queryVO = new RoleIdAndNameVO();
            queryVO.setRoleId(relationDO.getSubRoleId());
            queryVO.setRoleName(relationDO.getSubRoleName());
            return queryVO;
        }).collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(RoleIdAndNameVO::getRoleId))), ArrayList::new));

        return Wrapper.success(queryVOList);
    }

    /**
     * 根据下级渠道会员名称、下级渠道会员角色Id，模糊分页查询下级渠道会员列表
     *
     * @param headers HttpHeaders信息
     * @param pageVO  接口参数
     * @return 操作结果
     */
    @Override
    public Wrapper<PageData<MemberManageQueryVO>> pageLowerChannelMembersByNameAndRole(HttpHeaders headers, MemberManageChannelPageVO pageVO) {
        UserLoginCacheDTO loginUser = memberCacheService.checkUserFromCache(headers);

        List<Integer> memberTypeList = Stream.of(MemberTypeEnum.CHANNEL.getCode(), MemberTypeEnum.CHANNEL_PERSONAL.getCode()).collect(Collectors.toList());
        Specification<MemberRelationDO> specification = (root, query, criteriaBuilder) -> {
            List<Predicate> list = new ArrayList<>();

            list.add(criteriaBuilder.equal(root.get("memberId").as(Long.class), loginUser.getMemberId()));
            list.add(criteriaBuilder.equal(root.get("roleId").as(Long.class), loginUser.getMemberRoleId()));
            list.add(criteriaBuilder.equal(root.get("verified").as(Integer.class), MemberValidateStatusEnum.VERIFY_PASSED.getCode()));
            list.add(criteriaBuilder.equal(root.get("status").as(Integer.class), MemberStatusEnum.NORMAL.getCode()));
            //In查询
            Join<Object, Object> subRoleJoin = root.join("subRole", JoinType.LEFT);
            Expression<Integer> typeExp = subRoleJoin.get("memberType").get("typeEnum").as(Integer.class);
            list.add(typeExp.in(memberTypeList));

            if (StringUtils.hasLength(pageVO.getName())) {
                Join<Object, Object> subMemberJoin = root.join("subMember", JoinType.LEFT);
                list.add(criteriaBuilder.like(subMemberJoin.get("name").as(String.class), "%" + pageVO.getName().trim() + "%"));
            }

            if (!CollectionUtils.isEmpty(pageVO.getMemberIds())) {
                Expression<Long> exp = root.get("subMemberId").as(Long.class);
                list.add(exp.in(pageVO.getMemberIds()));
            }

            if (pageVO.getRoleId() != null && !pageVO.getRoleId().equals(0L)) {
                list.add(criteriaBuilder.equal(root.get("subRoleId").as(Long.class), pageVO.getRoleId()));
            }

            Predicate[] p = new Predicate[list.size()];
            return criteriaBuilder.and(list.toArray(p));
        };

        Pageable page = PageRequest.of(pageVO.getCurrent() - 1, pageVO.getPageSize(), Sort.by("id").ascending());
        Page<MemberRelationDO> pageList = relationRepository.findAll(specification, page);

        return Wrapper.success(new PageData<>(pageList.getTotalElements(), pageList.getContent().stream().map(relationDO -> {
            MemberManageQueryVO queryVO = new MemberManageQueryVO();
            queryVO.setId(relationDO.getId());
            queryVO.setMemberId(relationDO.getSubMemberId());
            queryVO.setName(relationDO.getSubMember().getName());
            queryVO.setMemberTypeName(MemberTypeEnum.getCodeMessage(relationDO.getSubRole().getMemberType().getTypeEnum()));
            queryVO.setRoleId(relationDO.getSubRoleId());
            queryVO.setRoleName(relationDO.getSubRoleName());
            queryVO.setLevelTag(relationDO.getLevelRight().getLevelTag());
            return queryVO;
        }).collect(Collectors.toList())));
    }

    /**
     * 根据下级会员名称，模糊分页查询会员角色为服务提供者的下级会员列表
     *
     * @param headers HttpHeaders信息
     * @param pageVO  接口参数
     * @return 操作结果
     */
    @Override
    public Wrapper<PageData<MemberManageQueryVO>> pageLowerProviderMembersByName(HttpHeaders headers, MemberManageNameWithExcludePageVO pageVO) {
        UserLoginCacheDTO loginUser = memberCacheService.checkUserFromCache(headers);
        Specification<MemberRelationDO> specification = (root, query, criteriaBuilder) -> {
            List<Predicate> list = new ArrayList<>();
            list.add(criteriaBuilder.equal(root.get("memberId").as(Long.class), loginUser.getMemberId()));
            list.add(criteriaBuilder.equal(root.get("roleId").as(Long.class), loginUser.getMemberRoleId()));
            list.add(criteriaBuilder.equal(root.get("verified").as(Integer.class), MemberValidateStatusEnum.VERIFY_PASSED.getCode()));
            list.add(criteriaBuilder.equal(root.get("status").as(Integer.class), MemberStatusEnum.NORMAL.getCode()));
            Join<Object, Object> subRoleJoin = root.join("subRole", JoinType.LEFT);
            list.add(criteriaBuilder.equal(subRoleJoin.get("roleType").get("typeEnum").as(Integer.class), RoleTypeEnum.SERVICE_PROVIDER.getCode()));

            //会员名称
            if (StringUtils.hasLength(pageVO.getName())) {
                Join<Object, Object> subMemberJoin = root.join("subMember", JoinType.LEFT);
                list.add(criteriaBuilder.like(subMemberJoin.get("name").as(String.class), "%" + pageVO.getName().trim() + "%"));
            }

            Predicate[] p = new Predicate[list.size()];
            return criteriaBuilder.and(list.toArray(p));
        };

        List<MemberRelationDO> relationDOList = relationRepository.findAll(specification, Sort.by("id").ascending());

        if (!CollectionUtils.isEmpty(pageVO.getExcludeList())) {
            relationDOList = relationDOList.stream().filter(r -> pageVO.getExcludeList().stream().noneMatch(memberExcludeVO -> memberExcludeVO.getMemberId().equals(r.getSubMemberId()) && memberExcludeVO.getRoleId().equals(r.getSubRoleId()))).collect(Collectors.toList());
        }

        int totalCount = relationDOList.size();
        List<MemberRelationDO> pageList = CollectionPageUtil.pageList(relationDOList, totalCount, pageVO.getCurrent(), pageVO.getPageSize());

        return Wrapper.success(new PageData<>((long) totalCount, pageList.stream().map(p -> {
            MemberManageQueryVO queryVO = new MemberManageQueryVO();
            queryVO.setId(p.getId());
            queryVO.setMemberId(p.getSubMemberId());
            queryVO.setName(p.getSubMember().getName());
            queryVO.setRoleId(p.getSubRoleId());
            queryVO.setRoleName(p.getSubRole().getRoleName());
            queryVO.setMemberTypeName(MemberTypeEnum.getCodeMessage(p.getSubRole().getMemberType().getTypeEnum()));
            queryVO.setLevel(p.getLevelRight().getLevel());
            queryVO.setLevelTag(p.getLevelRight().getLevelTag());
            return queryVO;
        }).collect(Collectors.toList())));
    }

    /**
     * 根据下级会员名称，模糊分页查询会员角色为服务消费者的下级会员列表
     *
     * @param headers HttpHeaders信息
     * @param pageVO  接口参数
     * @return 操作结果
     */
    @Override
    public Wrapper<PageData<MemberManageQueryVO>> pageLowerConsumerMembersByName(HttpHeaders headers, MemberManageNameWithExcludePageVO pageVO) {
        UserLoginCacheDTO loginUser = memberCacheService.checkUserFromCache(headers);
        Specification<MemberRelationDO> specification = (root, query, criteriaBuilder) -> {
            List<Predicate> list = new ArrayList<>();
            list.add(criteriaBuilder.equal(root.get("memberId").as(Long.class), loginUser.getMemberId()));
            list.add(criteriaBuilder.equal(root.get("roleId").as(Long.class), loginUser.getMemberRoleId()));
            list.add(criteriaBuilder.equal(root.get("verified").as(Integer.class), MemberValidateStatusEnum.VERIFY_PASSED.getCode()));
            list.add(criteriaBuilder.equal(root.get("status").as(Integer.class), MemberStatusEnum.NORMAL.getCode()));
            Join<Object, Object> subRoleJoin = root.join("subRole", JoinType.LEFT);
            list.add(criteriaBuilder.equal(subRoleJoin.get("roleType").get("typeEnum").as(Integer.class), RoleTypeEnum.SERVICE_CONSUMER.getCode()));

            //会员名称
            if (StringUtils.hasLength(pageVO.getName())) {
                Join<Object, Object> subMemberJoin = root.join("subMember", JoinType.LEFT);
                list.add(criteriaBuilder.like(subMemberJoin.get("name").as(String.class), "%" + pageVO.getName().trim() + "%"));
            }

            Predicate[] p = new Predicate[list.size()];
            return criteriaBuilder.and(list.toArray(p));
        };

        List<MemberRelationDO> relationDOList = relationRepository.findAll(specification, Sort.by("id").ascending());

        if (!CollectionUtils.isEmpty(pageVO.getExcludeList())) {
            relationDOList = relationDOList.stream().filter(r -> pageVO.getExcludeList().stream().noneMatch(memberExcludeVO -> memberExcludeVO.getMemberId().equals(r.getSubMemberId()) && memberExcludeVO.getRoleId().equals(r.getSubRoleId()))).collect(Collectors.toList());
        }

        int totalCount = relationDOList.size();
        List<MemberRelationDO> pageList = CollectionPageUtil.pageList(relationDOList, totalCount, pageVO.getCurrent(), pageVO.getPageSize());

        return Wrapper.success(new PageData<>((long) totalCount, pageList.stream().map(p -> {
            MemberManageQueryVO queryVO = new MemberManageQueryVO();
            queryVO.setId(p.getId());
            queryVO.setMemberId(p.getSubMemberId());
            queryVO.setName(p.getSubMember().getName());
            queryVO.setRoleId(p.getSubRoleId());
            queryVO.setRoleName(p.getSubRole().getRoleName());
            queryVO.setMemberTypeName(MemberTypeEnum.getCodeMessage(p.getSubRole().getMemberType().getTypeEnum()));
            queryVO.setLevel(p.getLevelRight().getLevel());
            queryVO.setLevelTag(p.getLevelRight().getLevelTag());
            return queryVO;
        }).collect(Collectors.toList())));
    }

    /**
     * 根据下级会员名称，模糊分页查询会员角色为服务消费者的下级渠道会员列表
     *
     * @param headers HttpHeaders信息
     * @param pageVO  接口参数
     * @return 操作结果
     */
    @Override
    public Wrapper<PageData<MemberManageQueryVO>> pageLowerConsumerMembersByName(HttpHeaders headers, MemberManagePageByNameVO pageVO) {
        UserLoginCacheDTO loginUser = memberCacheService.checkUserFromCache(headers);
        Pageable pageable = PageRequest.of(pageVO.getCurrent() - 1, pageVO.getPageSize(), Sort.by("id").ascending());
        Specification<MemberRelationDO> specification = (root, query, criteriaBuilder) -> {
            List<Predicate> list = new ArrayList<>();
            list.add(criteriaBuilder.equal(root.get("memberId").as(Long.class), loginUser.getMemberId()));
            list.add(criteriaBuilder.equal(root.get("roleId").as(Long.class), loginUser.getMemberRoleId()));
            list.add(criteriaBuilder.equal(root.get("verified").as(Integer.class), MemberValidateStatusEnum.VERIFY_PASSED.getCode()));
            list.add(criteriaBuilder.equal(root.get("status").as(Integer.class), MemberStatusEnum.NORMAL.getCode()));
            Join<Object, Object> subRoleJoin = root.join("subRole", JoinType.LEFT);
            list.add(criteriaBuilder.equal(subRoleJoin.get("roleType").get("typeEnum").as(Integer.class), RoleTypeEnum.SERVICE_CONSUMER.getCode()));

            //会员名称
            if (StringUtils.hasLength(pageVO.getName())) {
                Join<Object, Object> subMemberJoin = root.join("subMember", JoinType.LEFT);
                list.add(criteriaBuilder.like(subMemberJoin.get("name").as(String.class), "%" + pageVO.getName().trim() + "%"));
            }

            Predicate[] p = new Predicate[list.size()];
            return criteriaBuilder.and(list.toArray(p));
        };

        Page<MemberRelationDO> pageList = relationRepository.findAll(specification, pageable);
        return Wrapper.success(new PageData<>(pageList.getTotalElements(), pageList.getContent().stream().map(p -> {
            MemberManageQueryVO queryVO = new MemberManageQueryVO();
            queryVO.setId(p.getId());
            queryVO.setMemberId(p.getSubMemberId());
            queryVO.setName(p.getSubMember().getName());
            queryVO.setRoleId(p.getSubRoleId());
            queryVO.setRoleName(p.getSubRole().getRoleName());
            queryVO.setMemberTypeName(MemberTypeEnum.getCodeMessage(p.getSubRole().getMemberType().getTypeEnum()));
            queryVO.setLevel(p.getLevelRight().getLevel());
            queryVO.setLevelTag(p.getLevelRight().getLevelTag());
            return queryVO;
        }).collect(Collectors.toList())));
    }

    /**
     * 根据下级会员名称，模糊分页查询会员角色为服务提供者的下级“企业会员”列表
     *
     * @param headers HttpHeaders信息
     * @param pageVO  接口参数
     * @return 操作结果
     */
    @Override
    public Wrapper<PageData<MemberManageQueryVO>> pageLowerMerchantProviderMembersByName(HttpHeaders headers, MemberManagePageByNameVO pageVO) {
        UserLoginCacheDTO loginUser = memberCacheService.needLoginFromBusinessPlatform(headers);
        Specification<MemberRelationDO> specification = (root, query, criteriaBuilder) -> {
            List<Predicate> list = new ArrayList<>();
            list.add(criteriaBuilder.equal(root.get("memberId").as(Long.class), loginUser.getMemberId()));
            list.add(criteriaBuilder.equal(root.get("roleId").as(Long.class), loginUser.getMemberRoleId()));
            list.add(criteriaBuilder.equal(root.get("verified").as(Integer.class), MemberValidateStatusEnum.VERIFY_PASSED.getCode()));
            list.add(criteriaBuilder.equal(root.get("status").as(Integer.class), MemberStatusEnum.NORMAL.getCode()));

            Join<Object, Object> subRoleJoin = root.join("subRole", JoinType.LEFT);
            list.add(criteriaBuilder.or(criteriaBuilder.equal(subRoleJoin.get("memberType").get("typeEnum").as(Integer.class), MemberTypeEnum.MERCHANT.getCode()), criteriaBuilder.equal(subRoleJoin.get("memberType").get("typeEnum").as(Integer.class), MemberTypeEnum.MERCHANT_PERSONAL.getCode())));
            list.add(criteriaBuilder.equal(subRoleJoin.get("roleType").get("typeEnum").as(Integer.class), RoleTypeEnum.SERVICE_PROVIDER.getCode()));

            if (StringUtils.hasLength(pageVO.getName())) {
                Join<Object, Object> subMemberJoin = root.join("subMember", JoinType.LEFT);
                list.add(criteriaBuilder.like(subMemberJoin.get("name").as(String.class), "%" + pageVO.getName().trim() + "%"));
            }

            Predicate[] p = new Predicate[list.size()];
            return criteriaBuilder.and(list.toArray(p));
        };

        Pageable pageable = PageRequest.of(pageVO.getCurrent() - 1, pageVO.getPageSize(), Sort.by("id").ascending());
        Page<MemberRelationDO> pageList = relationRepository.findAll(specification, pageable);

        return Wrapper.success(new PageData<>(pageList.getTotalElements(), pageList.getContent().stream().map(relationDO -> {
            MemberManageQueryVO queryVO = new MemberManageQueryVO();
            queryVO.setId(relationDO.getId());
            queryVO.setMemberId(relationDO.getSubMemberId());
            queryVO.setName(relationDO.getSubMember().getName());
            queryVO.setRoleId(relationDO.getSubRoleId());
            queryVO.setRoleName(relationDO.getSubRoleName());
            queryVO.setLevel(relationDO.getLevelRight().getLevel());
            queryVO.setLevelTag(relationDO.getLevelRight().getLevelTag());
            queryVO.setMemberTypeName(MemberTypeEnum.getCodeMessage(relationDO.getSubRole().getMemberType().getTypeEnum()));
            return queryVO;
        }).collect(Collectors.toList())));
    }

    /**
     * 根据会员名称、商城类型分页查询会员列表
     *
     * @param headers HttpHeaders信息
     * @param pageVO  接口参数
     * @return 操作结果
     */
    @Override
    public Wrapper<PageData<MemberManageQueryVO>> pageMemberByNameAndMallType(HttpHeaders headers, MemberManagePageByNameAndMallTypeVO pageVO) {
        UserLoginCacheDTO loginUser = memberCacheService.checkUserFromCache(headers);

        Specification<MemberRelationDO> specification = (root, query, criteriaBuilder) -> {
            List<Predicate> list = new ArrayList<>();
            //上级会员id和角色Id
            list.add(criteriaBuilder.equal(root.get("memberId").as(Long.class), loginUser.getMemberId()));
            list.add(criteriaBuilder.equal(root.get("roleId").as(Long.class), loginUser.getMemberRoleId()));
            list.add(criteriaBuilder.equal(root.get("verified").as(Integer.class), MemberValidateStatusEnum.VERIFY_PASSED.getCode()));
            list.add(criteriaBuilder.equal(root.get("status").as(Integer.class), MemberStatusEnum.NORMAL.getCode()));

            Join<Object, Object> subRoleJoin = root.join("subRole", JoinType.LEFT);
            if (pageVO.getMemberTypeEnum() != null && !pageVO.getMemberTypeEnum().equals(0)) {
                list.add(criteriaBuilder.equal(subRoleJoin.get("memberType").get("typeEnum").as(Integer.class), pageVO.getMemberTypeEnum()));
            } else {
                if (pageVO.getMallType().equals(MALL_TYPE_ENTERPRISE) || pageVO.getMallType().equals(MALL_TYPE_SCORE)) {
                    list.add(criteriaBuilder.or(criteriaBuilder.equal(subRoleJoin.get("memberType").get("typeEnum").as(Integer.class), MemberTypeEnum.MERCHANT.getCode()), criteriaBuilder.equal(subRoleJoin.get("memberType").get("typeEnum").as(Integer.class), MemberTypeEnum.MERCHANT_PERSONAL.getCode())));
                } else {
                    list.add(criteriaBuilder.or(criteriaBuilder.equal(subRoleJoin.get("memberType").get("typeEnum").as(Integer.class), MemberTypeEnum.CHANNEL.getCode()), criteriaBuilder.equal(subRoleJoin.get("memberType").get("typeEnum").as(Integer.class), MemberTypeEnum.CHANNEL_PERSONAL.getCode())));
                }
            }

            if (StringUtils.hasLength(pageVO.getName())) {
                Join<Object, Object> subMemberJoin = root.join("subMember", JoinType.LEFT);
                list.add(criteriaBuilder.like(subMemberJoin.get("name").as(String.class), "%" + pageVO.getName() + "%"));
            }

            if (pageVO.getRoleId() != null && !pageVO.getRoleId().equals(0L)) {
                list.add(criteriaBuilder.equal(root.get("subRoleId").as(Long.class), pageVO.getRoleId()));
            }

            if (pageVO.getLevel() != null && !pageVO.getLevel().equals(0)) {
                Join<Object, Object> levelRightJoin = root.join("levelRight", JoinType.LEFT);
                list.add(criteriaBuilder.equal(levelRightJoin.get("level").as(Integer.class), pageVO.getLevel()));
            }

            Predicate[] p = new Predicate[list.size()];
            return criteriaBuilder.and(list.toArray(p));
        };

        Pageable pageable = PageRequest.of(pageVO.getCurrent() - 1, pageVO.getPageSize(), Sort.by("id").ascending());
        Page<MemberRelationDO> pageList = relationRepository.findAll(specification, pageable);

        return Wrapper.success(new PageData<>(pageList.getTotalElements(), pageList.getContent().stream().map(relationDO -> {
            MemberManageQueryVO queryVO = new MemberManageQueryVO();
            queryVO.setId(relationDO.getId());
            queryVO.setMemberId(relationDO.getSubMemberId());
            queryVO.setName(relationDO.getSubMember().getName());
            queryVO.setRoleId(relationDO.getSubRoleId());
            queryVO.setRoleName(relationDO.getSubRoleName());
            queryVO.setMemberTypeName(MemberTypeEnum.getCodeMessage(relationDO.getSubRole().getMemberType().getTypeEnum()));
            queryVO.setLevel(relationDO.getLevelRight().getLevel());
            queryVO.setLevelTag(relationDO.getLevelRight().getLevelTag());
            return queryVO;
        }).collect(Collectors.toList())));
    }

//    /**
//     * 根据上级会员Id和上级会员角色Id，以及当前用户，查询价格权益参数设置
//     *
//     * @param headers HttpHeaders信息
//     * @param upperVO 接口参数
//     * @return 操作结果
//     */
//    @Override
//    public Wrapper<MemberManageMemberCreditParameterVO> getUpperMemberCreditParameter(HttpHeaders headers, MemberManageUpperMemberAndRoleVO upperVO) {
//        UserLoginCacheDTO loginUser = memberCacheService.checkUserFromCache(headers);
//
//        MemberManageMemberCreditParameterVO parameterVO = new MemberManageMemberCreditParameterVO();
//        parameterVO.setParameter(new BigDecimal(1));
//        //查询上下级关系
//        MemberRelationDO relationDO = relationRepository.findFirstByMemberIdAndRoleIdAndSubMemberIdAndSubRoleId(upperVO.getParentMemberId(), upperVO.getParentMemberRoleId(), loginUser.getMemberId(), loginUser.getMemberRoleId());
//        if (relationDO == null || !relationDO.getVerified().equals(MemberValidateStatusEnum.VERIFY_PASSED.getCode()) || !relationDO.getStatus().equals(MemberStatusEnum.NORMAL.getCode())) {
//            return Wrapper.success(parameterVO);
//        }
//
//        MemberLevelRightDO levelRight = relationDO.getLevelRight();
//        if (levelRight == null) {
//            return Wrapper.success(parameterVO);
//        }
//
//        MemberLevelConfigDO levelConfig = levelRight.getLevelConfig();
//        if (levelConfig == null) {
//            return Wrapper.success(parameterVO);
//        }
//
//        if (CollectionUtils.isEmpty(levelConfig.getRights())) {
//            return Wrapper.success(parameterVO);
//        }
//
//        MemberRightConfigDO configDO = levelConfig.getRights().stream().filter(config -> config.getRightType().equals(MemberRightTypeEnum.PRICE_RIGHT.getCode())).findFirst().orElse(null);
//        if (configDO == null || configDO.getStatus().equals(EnableDisableStatus.DISABLE.getCode()) || configDO.getParameter().compareTo(BigDecimal.ZERO) == 0) {
//            return Wrapper.success(parameterVO);
//        }
//
//        parameterVO.setParameter(configDO.getParameter());
//
//        return Wrapper.success(parameterVO);
//    }

    /**
     * 根据上级会员Id和上级会员角色Id，以及当前用户，查询价格权益参数设置
     *
     * @param headers HttpHeaders信息
     * @param upperVO 接口参数
     * @return 操作结果
     */
    @Override
    public Wrapper<MemberManageMemberCreditParameterVO> getUpperMemberCreditParameter(HttpHeaders headers, MemberManageUpperMemberAndRoleVO upperVO) {
        UserLoginCacheDTO loginUser = memberCacheService.checkUserFromCache(headers);

        MemberManageMemberCreditParameterVO parameterVO = new MemberManageMemberCreditParameterVO();
        parameterVO.setParameter(new BigDecimal(1));
        //查询上下级关系
        MemberRelationDO relationDO = relationRepository.findFirstByMemberIdAndRoleIdAndSubMemberIdAndSubRoleId(upperVO.getParentMemberId(), upperVO.getParentMemberRoleId(), loginUser.getMemberId(), loginUser.getMemberRoleId());
        if (relationDO == null || !relationDO.getVerified().equals(MemberValidateStatusEnum.VERIFY_PASSED.getCode()) || !relationDO.getStatus().equals(MemberStatusEnum.NORMAL.getCode())) {
            return Wrapper.success(parameterVO);
        }

        MemberLevelRightDO levelRight = relationDO.getLevelRight();
        if (levelRight == null) {
            return Wrapper.success(parameterVO);
        }

        MemberLevelConfigDO levelConfig = levelRight.getLevelConfig();
        if (levelConfig == null) {
            return Wrapper.success(parameterVO);
        }

        if (CollectionUtils.isEmpty(levelConfig.getRights())) {
            return Wrapper.success(parameterVO);
        }

        MemberRightConfigDO configDO = levelConfig.getRights().stream().filter(config -> config.getRightType().equals(MemberRightTypeEnum.PRICE_RIGHT.getCode())).findFirst().orElse(null);
        if (configDO == null || configDO.getStatus().equals(EnableDisableStatus.DISABLE.getCode()) || configDO.getParameter().compareTo(BigDecimal.ZERO) == 0) {
            return Wrapper.success(parameterVO);
        }

        parameterVO.setParameter(configDO.getParameter());

        return Wrapper.success(parameterVO);
    }

    /**
     * 根据当前用户（上级会员），查询下级会员的价格权益参数设置
     *
     * @param headers HttpHeaders信息
     * @param subVO   接口参数
     * @return 操作结果
     */
    @Override
    public Wrapper<MemberManageMemberCreditParameterVO> getLowerMemberCreditParameter(HttpHeaders headers, SubMemberIdRoleIdVO subVO) {
        UserLoginCacheDTO loginUser = memberCacheService.checkUserFromCache(headers);

        MemberManageMemberCreditParameterVO parameterVO = new MemberManageMemberCreditParameterVO();
        parameterVO.setParameter(new BigDecimal(1));
        //查询上下级关系
        MemberRelationDO relationDO = relationRepository.findFirstByMemberIdAndRoleIdAndSubMemberIdAndSubRoleId(loginUser.getMemberId(), loginUser.getMemberRoleId(), subVO.getSubMemberId(), subVO.getSubRoleId());
        if (relationDO == null || !relationDO.getVerified().equals(MemberValidateStatusEnum.VERIFY_PASSED.getCode()) || !relationDO.getStatus().equals(MemberStatusEnum.NORMAL.getCode())) {
            return Wrapper.success(parameterVO);
        }

        MemberLevelRightDO levelRight = relationDO.getLevelRight();
        if (levelRight == null) {
            return Wrapper.success(parameterVO);
        }

        MemberLevelConfigDO levelConfig = levelRight.getLevelConfig();
        if (levelConfig == null) {
            return Wrapper.success(parameterVO);
        }

        if (CollectionUtils.isEmpty(levelConfig.getRights())) {
            return Wrapper.success(parameterVO);
        }

        MemberRightConfigDO configDO = levelConfig.getRights().stream().filter(config -> config.getRightType().equals(MemberRightTypeEnum.PRICE_RIGHT.getCode())).findFirst().orElse(null);
        if (configDO == null || configDO.getStatus().equals(EnableDisableStatus.DISABLE.getCode()) || configDO.getParameter().compareTo(BigDecimal.ZERO) == 0) {
            return Wrapper.success(parameterVO);
        }

        parameterVO.setParameter(configDO.getParameter());

        return Wrapper.success(parameterVO);
    }

    /**
     * 根据名称，模糊分页查询下级渠道会员列表
     *
     * @param headers HttpHeaders信息
     * @param pageVO  接口参数
     * @return 操作结果
     */
    @Override
    public Wrapper<PageData<MemberManageQueryVO>> pageLowerChannelMembersByNameAndRoleId(HttpHeaders headers, MemberManagePageByNameAndRoleIdVO pageVO) {
        UserLoginCacheDTO loginUser = memberCacheService.checkUserFromCache(headers);
        Specification<MemberRelationDO> specification = (root, query, criteriaBuilder) -> {
            List<Predicate> list = new ArrayList<>();
            //上级会员id和角色Id
            list.add(criteriaBuilder.equal(root.get("memberId").as(Long.class), loginUser.getMemberId()));
            list.add(criteriaBuilder.equal(root.get("roleId").as(Long.class), loginUser.getMemberRoleId()));
            list.add(criteriaBuilder.equal(root.get("verified").as(Integer.class), MemberValidateStatusEnum.VERIFY_PASSED.getCode()));
            list.add(criteriaBuilder.equal(root.get("status").as(Integer.class), MemberStatusEnum.NORMAL.getCode()));

            Join<Object, Object> subRoleJoin = root.join("subRole", JoinType.LEFT);
            list.add(criteriaBuilder.or(criteriaBuilder.equal(subRoleJoin.get("memberType").get("typeEnum").as(Integer.class), MemberTypeEnum.CHANNEL.getCode()),
                    criteriaBuilder.equal(subRoleJoin.get("memberType").get("typeEnum"), MemberTypeEnum.CHANNEL_PERSONAL.getCode())));

            if (StringUtils.hasLength(pageVO.getName())) {
                Join<Object, Object> subMemberJoin = root.join("subMember", JoinType.LEFT);
                list.add(criteriaBuilder.like(subMemberJoin.get("name").as(String.class), "%" + pageVO.getName().trim() + "%"));
            }

            if (pageVO.getRoleId() != null && !pageVO.getRoleId().equals(0L)) {
                list.add(criteriaBuilder.equal(root.get("subRoleId").as(Long.class), pageVO.getRoleId()));
            }

            Predicate[] p = new Predicate[list.size()];
            return criteriaBuilder.and(list.toArray(p));
        };

        Pageable page = PageRequest.of(pageVO.getCurrent() - 1, pageVO.getPageSize(), Sort.by("id").ascending());
        Page<MemberRelationDO> relationDOList = relationRepository.findAll(specification, page);

        return Wrapper.success(new PageData<>(relationDOList.getTotalElements(), relationDOList.getContent().stream().map(relationDO -> {
            MemberManageQueryVO queryVO = new MemberManageQueryVO();
            queryVO.setId(relationDO.getId());
            queryVO.setMemberId(relationDO.getSubMemberId());
            queryVO.setName(relationDO.getSubMember().getName());
            queryVO.setRoleId(relationDO.getSubRoleId());
            queryVO.setRoleName(relationDO.getSubRoleName());
            queryVO.setLevel(relationDO.getLevelRight().getLevel());
            queryVO.setLevelTag(relationDO.getLevelRight().getLevelTag());
            queryVO.setMemberTypeName(MemberTypeEnum.getCodeMessage(relationDO.getSubRole().getMemberType().getTypeEnum()));
            return queryVO;
        }).collect(Collectors.toList())));
    }

    /**
     * 根据下单类型和会员名称，模糊分页查询会员
     *
     * @param headers HttpHeaders信息
     * @param typeVO  接口参数
     * @return 操作结果
     */
    @Override
    public Wrapper<PageData<MemberManageQueryVO>> pageMembersByOrderTypeAndName(HttpHeaders headers, MemberManagePageByOrderTypeAndNameVO typeVO) {
        UserLoginCacheDTO loginUser = memberCacheService.checkUserFromCache(headers);

        long totalCount = 0;
        List<MemberManageQueryVO> queryVOList = new ArrayList<>();

        switch (MemberManageOrderTypeEnum.toEnum(typeVO.getOrderType())) {
            //下单模式手工下单、合并订单下单则供应会员数据来源于平台后台--平台会员管理中角色类型为服务提供的且会员类型为非渠道企业会员与非渠道个人会员的会员ID、会员名称、会员类型、会员角色、会员等级
            case MANUAL_ORDER:
            case COMBINED_ORDER:
                Pageable page = PageRequest.of(typeVO.getCurrent() - 1, typeVO.getPageSize(), Sort.by("id").ascending());
                Specification<MemberRelationDO> specification = (root, query, criteriaBuilder) -> {
                    List<Predicate> list = new ArrayList<>();
                    list.add(criteriaBuilder.equal(root.get("verified").as(Integer.class), MemberValidateStatusEnum.VERIFY_PASSED.getCode()));
                    list.add(criteriaBuilder.equal(root.get("status").as(Integer.class), MemberStatusEnum.NORMAL.getCode()));

                    list.add(criteriaBuilder.equal(root.get("relType").as(Integer.class), MemberRelationTypeEnum.PLATFORM.getCode()));
                    list.add(criteriaBuilder.notEqual(root.get("subMemberId").as(Long.class), loginUser.getMemberId()));
                    if (StringUtils.hasLength(typeVO.getName())) {
                        Join<Object, Object> subMemberJoin = root.join("subMember", JoinType.LEFT);
                        list.add(criteriaBuilder.like(subMemberJoin.get("name").as(String.class), "%" + typeVO.getName().trim() + "%"));
                    }

                    Join<Object, Object> subRoleJoin = root.join("subRole", JoinType.LEFT);
                    list.add(criteriaBuilder.equal(subRoleJoin.get("roleType").get("typeEnum").as(Integer.class), RoleTypeEnum.SERVICE_PROVIDER.getCode()));
                    list.add(criteriaBuilder.or(criteriaBuilder.equal(subRoleJoin.get("memberType").get("typeEnum").as(Integer.class), MemberTypeEnum.MERCHANT.getCode()), criteriaBuilder.equal(subRoleJoin.get("memberType").get("typeEnum").as(Integer.class), MemberTypeEnum.MERCHANT_PERSONAL.getCode())));

                    Predicate[] p = new Predicate[list.size()];
                    return criteriaBuilder.and(list.toArray(p));
                };
                Page<MemberRelationDO> pageList = relationRepository.findAll(specification, page);
                totalCount = pageList.getTotalElements();
                queryVOList = pageList.getContent().stream().map(relationDO -> {
                    MemberManageQueryVO queryVO = new MemberManageQueryVO();
                    queryVO.setId(relationDO.getId());
                    queryVO.setMemberId(relationDO.getSubMemberId());
                    queryVO.setName(relationDO.getSubMember().getName());
                    queryVO.setRoleId(relationDO.getSubRoleId());
                    queryVO.setRoleName(relationDO.getSubRoleName());
                    queryVO.setLevel(relationDO.getLevelRight().getLevel());
                    queryVO.setLevelTag(relationDO.getLevelRight().getLevelTag());
                    queryVO.setMemberTypeName(MemberTypeEnum.getCodeMessage(relationDO.getSubRole().getMemberType().getTypeEnum()));
                    return queryVO;
                }).collect(Collectors.toList());

                break;
            //下单模式渠道直采手工下单则供应会员数据来源于会员能力--会员管理中当前会员的会员归属（上级渠道）且会员类型为渠道企业会员与渠道个人会员的会员ID、会员名称、会员类型、会员角色、会员等级
            //下单模式渠道现货手工下单则供应会员数据来源于会员能力--会员管理中当前会员的会员归属且会员类型为渠道企业会员与渠道个人会员的会员ID、会员名称、会员类型、会员角色、会员等级
            case CHANNEL_DIRECT_MANUAL_ORDER:
            case CHANNEL_PRODUCT_MANUAL_ORDER:
                String name = StringUtils.hasLength(typeVO.getName()) ? typeVO.getName().trim() : "";
                List<MemberRelationDO> relationDOList = relationRepository.findBySubMemberIdAndSubRoleId(loginUser.getMemberId(), loginUser.getMemberRoleId()).stream().filter(relationDO -> relationDO.getMember().getName().contains(name) && (relationDO.getRole().getMemberType().getTypeEnum().equals(MemberTypeEnum.CHANNEL.getCode()) || relationDO.getRole().getMemberType().getTypeEnum().equals(MemberTypeEnum.CHANNEL_PERSONAL.getCode()))).sorted(Comparator.comparingLong(MemberRelationDO::getId)).collect(Collectors.toList());
                totalCount = relationDOList.size();

                List<MemberRelationDO> subList = CollectionPageUtil.pageList(relationDOList, typeVO.getCurrent(), typeVO.getPageSize());
                List<Long> subMemberIds = subList.stream().map(MemberRelationDO::getMemberId).collect(Collectors.toList());
                //查询与平台之间的关系，获得等级信息
                List<MemberRelationDO> platformMemberList = relationRepository.findByRelTypeAndSubMemberIdIn(MemberRelationTypeEnum.PLATFORM.getCode(), subMemberIds);

                queryVOList = subList.stream().map(relationDO -> {
                    MemberManageQueryVO queryVO = new MemberManageQueryVO();
                    queryVO.setId(relationDO.getId());
                    queryVO.setMemberId(relationDO.getMemberId());
                    queryVO.setName(relationDO.getMember().getName());
                    queryVO.setRoleId(relationDO.getRoleId());
                    queryVO.setRoleName(relationDO.getRole().getRoleName());
                    MemberRelationDO platformMemberRelation = platformMemberList.stream().filter(p -> p.getSubMemberId().equals(relationDO.getMemberId()) && p.getSubRoleId().equals(relationDO.getRoleId())).findFirst().orElse(null);
                    queryVO.setLevel(platformMemberRelation == null ? 0 : platformMemberRelation.getLevelRight().getLevel());
                    queryVO.setLevelTag(platformMemberRelation == null ? "" : platformMemberRelation.getLevelRight().getLevelTag());
                    queryVO.setMemberTypeName(MemberTypeEnum.getCodeMessage(relationDO.getRole().getMemberType().getTypeEnum()));
                    return queryVO;
                }).collect(Collectors.toList());
                break;
            default:
                break;
        }

        return Wrapper.success(new PageData<>(totalCount, queryVOList));
    }

    /**
     * 分页查询会员列表页面搜索条件内容
     *
     * @param headers HttpHeaders信息
     * @return 查询结果
     */
    @Override
    public Wrapper<MemberManageSearchConditionVO> getPageSearchConditions(HttpHeaders headers, MemberManageMemberItemVO itemVO) {
        MemberManageSearchConditionVO conditionVO = new MemberManageSearchConditionVO();
        //会员类型
        conditionVO.setMemberTypes(memberTypeRepository.findAll().stream().map(memberTypeDO -> new MemberTypeIdAndNameVO(memberTypeDO.getId(), MemberTypeEnum.getCodeMessage(memberTypeDO.getTypeEnum()))).sorted(Comparator.comparingLong(MemberTypeIdAndNameVO::getMemberTypeId)).collect(Collectors.toList()));
        //角色
        List<RoleDO> roleDOList = roleRepository.findAll();
        if (itemVO.getRoleTypeEnum() != null && !itemVO.getRoleTypeEnum().equals(0)) {
            conditionVO.setRoles(roleDOList.stream().filter(roleDO -> !roleDO.getRelType().equals(MemberRelationTypeEnum.PLATFORM.getCode()) && roleDO.getRoleType().getTypeEnum().equals(itemVO.getRoleTypeEnum())).map(roleDO -> new RoleIdAndNameVO(roleDO.getId(), roleDO.getRoleName())).sorted(Comparator.comparingLong(RoleIdAndNameVO::getRoleId)).collect(Collectors.toList()));
        } else {
            conditionVO.setRoles(roleDOList.stream().filter(roleDO -> !roleDO.getRelType().equals(MemberRelationTypeEnum.PLATFORM.getCode())).map(roleDO -> new RoleIdAndNameVO(roleDO.getId(), roleDO.getRoleName())).sorted(Comparator.comparingLong(RoleIdAndNameVO::getRoleId)).collect(Collectors.toList()));
        }

        //等级
        List<LevelAndTagVO> levelList = baseLevelConfigRepository.findAll().stream().map(memberLevelConfigDO -> new LevelAndTagVO(memberLevelConfigDO.getLevel(), memberLevelConfigDO.getLevelTag()))
                .collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(LevelAndTagVO::getLevel))), ArrayList::new))
                .stream().sorted(Comparator.comparing(LevelAndTagVO::getLevel)).collect(Collectors.toList());
        conditionVO.setLevels(levelList);

        return Wrapper.success(conditionVO);
    }

    /**
     * 根据当前登录会员，查询下级会员角色列表
     *
     * @param headers Http头部信息
     * @return 查询结果
     */
    @Override
    public Wrapper<List<RoleIdAndNameVO>> getSubRoleListByMember(HttpHeaders headers) {
        UserLoginCacheDTO loginUser = memberCacheService.needLoginFromBusinessPlatform(headers);
        Integer memberTypeEnum = loginUser.getMemberType();
        Specification<RoleDO> specification = (root, query, criteriaBuilder) -> {
            List<Predicate> list = new ArrayList<>();
            list.add(criteriaBuilder.notEqual(root.get("relType").as(Integer.class), MemberRelationTypeEnum.PLATFORM.getCode()));
            list.add(criteriaBuilder.equal(root.get("status").as(Integer.class), EnableDisableStatus.ENABLE.getCode()));

            Join<Object, Object> memberTypeJoin = root.join("memberType", JoinType.LEFT);
            if (memberTypeEnum.equals(MemberTypeEnum.MERCHANT.getCode()) || memberTypeEnum.equals(MemberTypeEnum.MERCHANT_PERSONAL.getCode())) {
                list.add(criteriaBuilder.or(criteriaBuilder.equal(memberTypeJoin.get("typeEnum").as(Integer.class), MemberTypeEnum.MERCHANT.getCode()), criteriaBuilder.equal(memberTypeJoin.get("typeEnum").as(Integer.class), MemberTypeEnum.MERCHANT_PERSONAL.getCode())));
            } else {
                list.add(criteriaBuilder.or(criteriaBuilder.equal(memberTypeJoin.get("typeEnum").as(Integer.class), MemberTypeEnum.CHANNEL.getCode()), criteriaBuilder.equal(memberTypeJoin.get("typeEnum").as(Integer.class), MemberTypeEnum.CHANNEL_PERSONAL.getCode())));
            }

            Predicate[] p = new Predicate[list.size()];
            return criteriaBuilder.and(list.toArray(p));
        };

        return Wrapper.success(roleRepository.findAll(specification).stream().map(roleDO -> new RoleIdAndNameVO(roleDO.getId(), roleDO.getRoleName())).collect(Collectors.toList()));
    }

    /**
     * “新增仓位存储”：根据商城类型分页查询会员
     *
     * @param headers HttpHeaders信息
     * @param typeVO  接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<PageData<MemberManageQueryVO>> pageMembersByShopType(HttpHeaders headers, MemberManagePageByShopTypeVO typeVO) {
        UserLoginCacheDTO loginUser = memberCacheService.needLoginFromBusinessPlatform(headers);

        //当前选择的商城类型为企业商城、积分商城时，会员数据来源于会员能力--会员管理中当前会员所属的（下级）商户会员且角色为消费者类型
        //当前选择的商城类型为渠道商城、渠道自有商城、渠道积分商城时，会员数据来源于商品能力--渠道商品管理中当前商品已上架的适用渠道
        Pageable page = PageRequest.of(typeVO.getCurrent() - 1, typeVO.getPageSize(), Sort.by("id").ascending());
        if (typeVO.getShopType().equals(ShopTypeEnum.ENTERPRISE.getCode()) || typeVO.getShopType().equals(ShopTypeEnum.SCORE.getCode())) {
            Specification<MemberRelationDO> specification = (root, query, criteriaBuilder) -> {
                List<Predicate> list = new ArrayList<>();

                list.add(criteriaBuilder.equal(root.get("memberId").as(Long.class), loginUser.getMemberId()));
                list.add(criteriaBuilder.equal(root.get("roleId").as(Long.class), loginUser.getMemberRoleId()));
                list.add(criteriaBuilder.equal(root.get("relType").as(Integer.class), MemberRelationTypeEnum.OTHER.getCode()));
                list.add(criteriaBuilder.equal(root.get("verified").as(Integer.class), MemberValidateStatusEnum.VERIFY_PASSED.getCode()));
                list.add(criteriaBuilder.equal(root.get("status").as(Integer.class), MemberStatusEnum.NORMAL.getCode()));

                Join<Object, Object> subRoleJoin = root.join("subRole", JoinType.LEFT);
                list.add(criteriaBuilder.or(criteriaBuilder.equal(subRoleJoin.get("memberType").get("typeEnum").as(Integer.class), MemberTypeEnum.MERCHANT.getCode()),
                        criteriaBuilder.equal(subRoleJoin.get("memberType").get("typeEnum").as(Integer.class), MemberTypeEnum.MERCHANT_PERSONAL.getCode())));
                list.add(criteriaBuilder.equal(subRoleJoin.get("roleType").get("typeEnum").as(Integer.class), RoleTypeEnum.SERVICE_CONSUMER.getCode()));

                //会员名称
                if (StringUtils.hasLength(typeVO.getName())) {
                    Join<Object, Object> subMemberJoin = root.join("subMember", JoinType.LEFT);
                    list.add(criteriaBuilder.like(subMemberJoin.get("name").as(String.class), "%" + typeVO.getName().trim() + "%"));
                }

                //会员角色
                if (typeVO.getRoleId() != null && !typeVO.getRoleId().equals(0L)) {
                    list.add(criteriaBuilder.equal(root.get("subRoleId").as(Long.class), typeVO.getRoleId()));
                }

                //会员类型
                if (typeVO.getMemberTypeId() != null && !typeVO.getMemberTypeId().equals(0L)) {
                    list.add(criteriaBuilder.equal(subRoleJoin.get("memberType").get("id").as(Long.class), typeVO.getMemberTypeId()));
                }

                //等级
                if (typeVO.getLevel() != null && !typeVO.getLevel().equals(0)) {
                    Join<Object, Object> levelRightJoin = root.join("levelRight", JoinType.LEFT);
                    list.add(criteriaBuilder.equal(levelRightJoin.get("level").as(Integer.class), typeVO.getLevel()));
                }

                Predicate[] p = new Predicate[list.size()];
                return criteriaBuilder.and(list.toArray(p));
            };

            Page<MemberRelationDO> pageList = relationRepository.findAll(specification, page);
            return Wrapper.success(new PageData<>(pageList.getTotalElements(), pageList.getContent().stream().map(relationDO -> {
                MemberManageQueryVO queryVO = new MemberManageQueryVO();
                queryVO.setId(relationDO.getId());
                queryVO.setMemberId(relationDO.getSubMemberId());
                queryVO.setName(relationDO.getSubMember().getName());
                queryVO.setMemberTypeName(MemberTypeEnum.getCodeMessage(relationDO.getSubRole().getMemberType().getTypeEnum()));
                queryVO.setLevel(relationDO.getLevelRight().getLevel());
                queryVO.setLevelTag(relationDO.getLevelRight().getLevelTag());
                queryVO.setRoleId(relationDO.getSubRoleId());
                queryVO.setRoleName(relationDO.getSubRole().getRoleName());
                return queryVO;
            }).collect(Collectors.toList())));
        } else {
            Specification<MemberRelationDO> specification = (root, query, criteriaBuilder) -> {
                List<Predicate> list = new ArrayList<>();
                list.add(criteriaBuilder.equal(root.get("memberId").as(Long.class), loginUser.getMemberId()));
                list.add(criteriaBuilder.equal(root.get("roleId").as(Long.class), loginUser.getMemberRoleId()));
                list.add(criteriaBuilder.equal(root.get("verified").as(Integer.class), MemberValidateStatusEnum.VERIFY_PASSED.getCode()));
                list.add(criteriaBuilder.equal(root.get("status").as(Integer.class), MemberStatusEnum.NORMAL.getCode()));

                //会员名称
                if (StringUtils.hasLength(typeVO.getName())) {
                    Join<Object, Object> subMemberJoin = root.join("subMember", JoinType.LEFT);
                    list.add(criteriaBuilder.like(subMemberJoin.get("name").as(String.class), "%" + typeVO.getName().trim() + "%"));
                }

                //陈璟发(测试)说这里的角色要为消费者类型
                Join<Object, Object> subRoleJoin = root.join("subRole", JoinType.LEFT);
                list.add(criteriaBuilder.or(criteriaBuilder.equal(subRoleJoin.get("memberType").get("typeEnum").as(Integer.class), MemberTypeEnum.CHANNEL.getCode()), criteriaBuilder.equal(subRoleJoin.get("memberType").get("typeEnum").as(Integer.class), MemberTypeEnum.CHANNEL_PERSONAL.getCode())));
                list.add(criteriaBuilder.equal(subRoleJoin.get("roleType").get("typeEnum").as(Integer.class), RoleTypeEnum.SERVICE_CONSUMER.getCode()));

                //会员类型
                if (typeVO.getMemberTypeId() != null && !typeVO.getMemberTypeId().equals(0L)) {
                    list.add(criteriaBuilder.equal(subRoleJoin.get("memberType").get("id").as(Long.class), typeVO.getMemberTypeId()));
                }

                //会员角色
                if (typeVO.getRoleId() != null && !typeVO.getRoleId().equals(0L)) {
                    list.add(criteriaBuilder.equal(root.get("subRoleId").as(Long.class), typeVO.getRoleId()));
                }

                //Or查询。如果会员Id为0，则查询角色
                if (!CollectionUtils.isEmpty(typeVO.getMembers())) {
                    List<Predicate> orList = new ArrayList<>();
                    for (MemberAndRoleIdVO item : typeVO.getMembers()) {
                        Long subMemberId = item.getMemberId();
                        Long subRoleId = item.getRoleId();
                        if ((subMemberId != null && !subMemberId.equals(0L)) && (subRoleId != null && !subRoleId.equals(0L))) {
                            orList.add(criteriaBuilder.and(criteriaBuilder.equal(root.get("subMemberId").as(Long.class), subMemberId), criteriaBuilder.equal(root.get("subRoleId").as(Long.class), subRoleId)));
                        } else if (subRoleId != null && !subRoleId.equals(0L)) {
                            orList.add(criteriaBuilder.equal(root.get("subRoleId").as(Long.class), subRoleId));
                        } else {
                            orList.add(criteriaBuilder.equal(root.get("subMemberId").as(Long.class), subMemberId));
                        }

                    }
                    Predicate[] orP = new Predicate[orList.size()];
                    list.add(criteriaBuilder.or(orList.toArray(orP)));
                }

                //等级
                if (typeVO.getLevel() != null && !typeVO.getLevel().equals(0)) {
                    Join<Object, Object> levelRightJoin = root.join("levelRight", JoinType.LEFT);
                    list.add(criteriaBuilder.equal(levelRightJoin.get("level").as(Integer.class), typeVO.getLevel()));
                }


                Predicate[] p = new Predicate[list.size()];
                return criteriaBuilder.and(list.toArray(p));
            };

            Page<MemberRelationDO> pageList = relationRepository.findAll(specification, page);
            return Wrapper.success(new PageData<>(pageList.getTotalElements(), pageList.getContent().stream().map(relationDO -> {
                MemberManageQueryVO queryVO = new MemberManageQueryVO();
                queryVO.setId(relationDO.getId());
                queryVO.setMemberId(relationDO.getSubMemberId());
                queryVO.setName(relationDO.getSubMember().getName());
                queryVO.setMemberTypeName(MemberTypeEnum.getCodeMessage(relationDO.getSubRole().getMemberType().getTypeEnum()));
                queryVO.setLevel(relationDO.getLevelRight().getLevel());
                queryVO.setLevelTag(relationDO.getLevelRight().getLevelTag());
                queryVO.setRoleId(relationDO.getSubRoleId());
                queryVO.setRoleName(relationDO.getSubRoleName());
                return queryVO;
            }).collect(Collectors.toList())));
        }
    }

    /**
     * 分页查询角色为“服务提供者”的会员列表
     *
     * @param headers Http头部信息
     * @param pageVO  接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<PageData<MemberManageQueryVO>> pageMembersByServiceProviderRole(HttpHeaders headers, MemberManagePageVO pageVO) {
        memberCacheService.checkUserFromCache(headers);

        Specification<MemberRelationDO> specification = (root, query, criteriaBuilder) -> {
            List<Predicate> list = new ArrayList<>();
            list.add(criteriaBuilder.equal(root.get("relType").as(Integer.class), MemberRelationTypeEnum.PLATFORM.getCode()));
            list.add(criteriaBuilder.equal(root.get("verified").as(Integer.class), MemberValidateStatusEnum.VERIFY_PASSED.getCode()));
            list.add(criteriaBuilder.equal(root.get("status").as(Integer.class), MemberStatusEnum.NORMAL.getCode()));

            //下级会员角色为服务提供者
            Join<Object, Object> subRoleJoin = root.join("subRole", JoinType.LEFT);
            list.add(criteriaBuilder.equal(subRoleJoin.get("roleType").get("typeEnum").as(Integer.class), RoleTypeEnum.SERVICE_PROVIDER.getCode()));

            //会员名称
            if (StringUtils.hasLength(pageVO.getName())) {
                Join<Object, Object> subMemberJoin = root.join("subMember", JoinType.LEFT);
                list.add(criteriaBuilder.like(subMemberJoin.get("name").as(String.class), "%" + pageVO.getName().trim() + "%"));
            }

            //会员类型
            if (pageVO.getMemberTypeId() != null && !pageVO.getMemberTypeId().equals(0L)) {
                list.add(criteriaBuilder.equal(subRoleJoin.get("memberType").get("id").as(Long.class), pageVO.getMemberTypeId()));
            }

            //角色Id
            if (pageVO.getRoleId() != null && !pageVO.getRoleId().equals(0L)) {
                list.add(criteriaBuilder.equal(root.get("subRoleId").as(Long.class), pageVO.getRoleId()));
            }

            //等级
            if (pageVO.getLevel() != null && !pageVO.getLevel().equals(0)) {
                Join<Object, Object> levelRightJoin = root.join("levelRight", JoinType.LEFT);
                list.add(criteriaBuilder.equal(levelRightJoin.get("level").as(Integer.class), pageVO.getLevel()));
            }

            Predicate[] p = new Predicate[list.size()];
            return criteriaBuilder.and(list.toArray(p));
        };

        Pageable page = PageRequest.of(pageVO.getCurrent() - 1, pageVO.getPageSize(), Sort.by("id").ascending());
        Page<MemberRelationDO> pageList = relationRepository.findAll(specification, page);
        return Wrapper.success(new PageData<>(pageList.getTotalElements(), pageList.getContent().stream().map(relationDO -> {
            MemberManageQueryVO queryVO = new MemberManageQueryVO();
            queryVO.setId(relationDO.getId());
            queryVO.setMemberId(relationDO.getSubMemberId());
            queryVO.setName(relationDO.getSubMember().getName());
            queryVO.setMemberTypeName(MemberTypeEnum.getCodeMessage(relationDO.getSubRole().getMemberType().getTypeEnum()));
            queryVO.setLevel(relationDO.getLevelRight().getLevel());
            queryVO.setLevelTag(relationDO.getLevelRight().getLevelTag());
            queryVO.setRoleId(relationDO.getSubRoleId());
            queryVO.setRoleName(relationDO.getSubRoleName());
            return queryVO;
        }).collect(Collectors.toList())));
    }

    /**
     * 分页查询角色为“服务消费者”的平台会员列表
     *
     * @param headers Http头部信息
     * @param pageVO  接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<PageData<MemberManageQueryVO>> pageMembersByServiceConsumerRole(HttpHeaders headers, MemberManagePageVO pageVO) {
        memberCacheService.checkUserFromCache(headers);

        Specification<MemberRelationDO> specification = (root, query, criteriaBuilder) -> {
            List<Predicate> list = new ArrayList<>();
            list.add(criteriaBuilder.equal(root.get("relType").as(Integer.class), MemberRelationTypeEnum.PLATFORM.getCode()));
            list.add(criteriaBuilder.equal(root.get("verified").as(Integer.class), MemberValidateStatusEnum.VERIFY_PASSED.getCode()));
            list.add(criteriaBuilder.equal(root.get("status").as(Integer.class), MemberStatusEnum.NORMAL.getCode()));

            //下级会员角色为服务消费者
            Join<Object, Object> subRoleJoin = root.join("subRole", JoinType.LEFT);
            list.add(criteriaBuilder.equal(subRoleJoin.get("roleType").get("typeEnum").as(Integer.class), RoleTypeEnum.SERVICE_CONSUMER.getCode()));

            //会员名称
            if (StringUtils.hasLength(pageVO.getName())) {
                Join<Object, Object> subMemberJoin = root.join("subMember", JoinType.LEFT);
                list.add(criteriaBuilder.like(subMemberJoin.get("name").as(String.class), "%" + pageVO.getName().trim() + "%"));
            }

            //会员类型
            if (pageVO.getMemberTypeId() != null && !pageVO.getMemberTypeId().equals(0L)) {
                list.add(criteriaBuilder.equal(subRoleJoin.get("memberType").get("id").as(Long.class), pageVO.getMemberTypeId()));
            }

            //角色Id
            if (pageVO.getRoleId() != null && !pageVO.getRoleId().equals(0L)) {
                list.add(criteriaBuilder.equal(root.get("subRoleId").as(Long.class), pageVO.getRoleId()));
            }

            //等级
            if (pageVO.getLevel() != null && !pageVO.getLevel().equals(0)) {
                Join<Object, Object> levelRightJoin = root.join("levelRight", JoinType.LEFT);
                list.add(criteriaBuilder.equal(levelRightJoin.get("level").as(Integer.class), pageVO.getLevel()));
            }

            Predicate[] p = new Predicate[list.size()];
            return criteriaBuilder.and(list.toArray(p));
        };

        Pageable page = PageRequest.of(pageVO.getCurrent() - 1, pageVO.getPageSize(), Sort.by("id").ascending());
        Page<MemberRelationDO> pageList = relationRepository.findAll(specification, page);
        return Wrapper.success(new PageData<>(pageList.getTotalElements(), pageList.getContent().stream().map(relationDO -> {
            MemberManageQueryVO queryVO = new MemberManageQueryVO();
            queryVO.setId(relationDO.getId());
            queryVO.setMemberId(relationDO.getSubMemberId());
            queryVO.setName(relationDO.getSubMember().getName());
            queryVO.setMemberTypeName(MemberTypeEnum.getCodeMessage(relationDO.getSubRole().getMemberType().getTypeEnum()));
            queryVO.setLevel(relationDO.getLevelRight().getLevel());
            queryVO.setLevelTag(relationDO.getLevelRight().getLevelTag());
            queryVO.setRoleId(relationDO.getSubRoleId());
            queryVO.setRoleName(relationDO.getSubRoleName());
            return queryVO;
        }).collect(Collectors.toList())));
    }

    /**
     * 根据会员名称，分页查询角色类型为服务提供者的平台商户会员
     *
     * @param headers Http头部信息
     * @param pageVO  接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<PageData<MemberManageQueryVO>> pagePlatformServiceProviderMerchantMember(HttpHeaders headers, MemberManagePageByNameVO pageVO) {
        memberCacheService.checkUserFromCache(headers);
        Specification<MemberRelationDO> specification = (root, query, criteriaBuilder) -> {
            List<Predicate> list = new ArrayList<>();
            list.add(criteriaBuilder.equal(root.get("relType").as(Integer.class), MemberRelationTypeEnum.PLATFORM.getCode()));
            list.add(criteriaBuilder.equal(root.get("verified").as(Integer.class), MemberValidateStatusEnum.VERIFY_PASSED.getCode()));
            list.add(criteriaBuilder.equal(root.get("status").as(Integer.class), MemberStatusEnum.NORMAL.getCode()));

            //下级会员角色为服务提供者
            Join<Object, Object> subRoleJoin = root.join("subRole", JoinType.LEFT);
            list.add(criteriaBuilder.equal(subRoleJoin.get("roleType").get("typeEnum").as(Integer.class), RoleTypeEnum.SERVICE_PROVIDER.getCode()));
            list.add(criteriaBuilder.or(criteriaBuilder.equal(subRoleJoin.get("memberType").get("typeEnum").as(Integer.class), MemberTypeEnum.MERCHANT.getCode()), criteriaBuilder.equal(subRoleJoin.get("memberType").get("typeEnum").as(Integer.class), MemberTypeEnum.MERCHANT_PERSONAL.getCode())));

            // 下级会员名称
            if (StringUtils.hasLength(pageVO.getName())) {
                Join<Object, Object> subMemberJoin = root.join("subMember", JoinType.LEFT);
                list.add(criteriaBuilder.like(subMemberJoin.get("name").as(String.class), "%" + pageVO.getName().trim() + "%"));
            }

            Predicate[] p = new Predicate[list.size()];
            return criteriaBuilder.and(list.toArray(p));
        };

        Pageable page = PageRequest.of(pageVO.getCurrent() - 1, pageVO.getPageSize(), Sort.by("id").ascending());
        Page<MemberRelationDO> pageList = relationRepository.findAll(specification, page);
        return Wrapper.success(new PageData<>(pageList.getTotalElements(), pageList.getContent().stream().map(relationDO -> {
            MemberManageQueryVO queryVO = new MemberManageQueryVO();
            queryVO.setId(relationDO.getId());
            queryVO.setMemberId(relationDO.getSubMemberId());
            queryVO.setName(relationDO.getSubMember().getName());
            queryVO.setMemberTypeName(MemberTypeEnum.getCodeMessage(relationDO.getSubRole().getMemberType().getTypeEnum()));
            queryVO.setLevel(relationDO.getLevelRight() == null ? 0 : relationDO.getLevelRight().getLevel());
            queryVO.setLevelTag(relationDO.getLevelRight() == null ? "" : relationDO.getLevelRight().getLevelTag());
            queryVO.setRoleId(relationDO.getSubRoleId());
            queryVO.setRoleName(relationDO.getSubRoleName());
            return queryVO;
        }).collect(Collectors.toList())));
    }

    /**
     * 根据会员名称，分页查询角色类型为服务提供者的平台企业会员（非企业个人会员）
     *
     * @param headers Http头部信息
     * @param pageVO  接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<PageData<MemberManageQueryVO>> pagePlatformServiceProviderEnterpriseMember(HttpHeaders headers, MemberManagePageByNameVO pageVO) {
        memberCacheService.checkUserFromCache(headers);
        Specification<MemberRelationDO> specification = (root, query, criteriaBuilder) -> {
            List<Predicate> list = new ArrayList<>();
            list.add(criteriaBuilder.equal(root.get("relType").as(Integer.class), MemberRelationTypeEnum.PLATFORM.getCode()));
            list.add(criteriaBuilder.equal(root.get("verified").as(Integer.class), MemberValidateStatusEnum.VERIFY_PASSED.getCode()));
            list.add(criteriaBuilder.equal(root.get("status").as(Integer.class), MemberStatusEnum.NORMAL.getCode()));

            //下级会员角色为服务提供者、会员类型为“企业会员”
            Join<Object, Object> subRoleJoin = root.join("subRole", JoinType.LEFT);
            list.add(criteriaBuilder.equal(subRoleJoin.get("roleType").get("typeEnum").as(Integer.class), RoleTypeEnum.SERVICE_PROVIDER.getCode()));
            list.add(criteriaBuilder.equal(subRoleJoin.get("memberType").get("typeEnum").as(Integer.class), MemberTypeEnum.MERCHANT.getCode()));

            // 下级会员名称
            if (StringUtils.hasLength(pageVO.getName())) {
                Join<Object, Object> subMemberJoin = root.join("subMember", JoinType.LEFT);
                list.add(criteriaBuilder.like(subMemberJoin.get("name").as(String.class), "%" + pageVO.getName().trim() + "%"));
            }

            Predicate[] p = new Predicate[list.size()];
            return criteriaBuilder.and(list.toArray(p));
        };

        Pageable page = PageRequest.of(pageVO.getCurrent() - 1, pageVO.getPageSize(), Sort.by("id").ascending());
        Page<MemberRelationDO> pageList = relationRepository.findAll(specification, page);
        return Wrapper.success(new PageData<>(pageList.getTotalElements(), pageList.getContent().stream().map(relationDO -> {
            MemberManageQueryVO queryVO = new MemberManageQueryVO();
            queryVO.setId(relationDO.getId());
            queryVO.setMemberId(relationDO.getSubMemberId());
            queryVO.setName(relationDO.getSubMember().getName());
            queryVO.setMemberTypeName(MemberTypeEnum.getCodeMessage(relationDO.getSubRole().getMemberType().getTypeEnum()));
            queryVO.setLevel(relationDO.getLevelRight().getLevel());
            queryVO.setLevelTag(relationDO.getLevelRight().getLevelTag());
            queryVO.setRoleId(relationDO.getSubRoleId());
            queryVO.setRoleName(relationDO.getSubRoleName());
            return queryVO;
        }).collect(Collectors.toList())));
    }

    /**
     * 根据会员名称，分页查询角色为服务提供者的上级会员列表
     *
     * @param headers      Http头部信息
     * @param pageByNameVO 接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<PageData<MemberManageQueryVO>> pageUpperProviderMember(HttpHeaders headers, MemberManagePageByNameVO pageByNameVO) {
        UserLoginCacheDTO loginUser = memberCacheService.needLoginFromBusinessPlatform(headers);

        Specification<MemberRelationDO> specification = (root, query, criteriaBuilder) -> {
            List<Predicate> list = new ArrayList<>();
            list.add(criteriaBuilder.equal(root.get("relType").as(Integer.class), MemberRelationTypeEnum.OTHER.getCode()));
            list.add(criteriaBuilder.equal(root.get("subMemberId").as(Long.class), loginUser.getMemberId()));
            list.add(criteriaBuilder.equal(root.get("subRoleId").as(Long.class), loginUser.getMemberRoleId()));
            list.add(criteriaBuilder.equal(root.get("verified").as(Integer.class), MemberValidateStatusEnum.VERIFY_PASSED.getCode()));
            list.add(criteriaBuilder.equal(root.get("status").as(Integer.class), MemberStatusEnum.NORMAL.getCode()));

            //上级会员角色为服务提供者
            Join<Object, Object> roleJoin = root.join("role", JoinType.LEFT);
            list.add(criteriaBuilder.equal(roleJoin.get("roleType").get("typeEnum").as(Integer.class), RoleTypeEnum.SERVICE_PROVIDER.getCode()));

            // 上级会员名称
            if (StringUtils.hasLength(pageByNameVO.getName())) {
                Join<Object, Object> memberJoin = root.join("member", JoinType.LEFT);
                list.add(criteriaBuilder.like(memberJoin.get("name").as(String.class), "%" + pageByNameVO.getName().trim() + "%"));
            }

            Predicate[] p = new Predicate[list.size()];
            return criteriaBuilder.and(list.toArray(p));
        };

        Pageable page = PageRequest.of(pageByNameVO.getCurrent() - 1, pageByNameVO.getPageSize(), Sort.by("id").ascending());
        Page<MemberRelationDO> pageList = relationRepository.findAll(specification, page);
        return Wrapper.success(new PageData<>(pageList.getTotalElements(), pageList.getContent().stream().map(relationDO -> {
            MemberManageQueryVO queryVO = new MemberManageQueryVO();
            queryVO.setId(relationDO.getId());
            queryVO.setMemberId(relationDO.getMemberId());
            queryVO.setName(relationDO.getMember().getName());
            queryVO.setMemberTypeName(MemberTypeEnum.getCodeMessage(relationDO.getRole().getMemberType().getTypeEnum()));
            queryVO.setLevel(relationDO.getLevelRight().getLevel());
            queryVO.setLevelTag(relationDO.getLevelRight().getLevelTag());
            queryVO.setRoleId(relationDO.getRoleId());
            queryVO.setRoleName(relationDO.getRole().getRoleName());
            return queryVO;
        }).collect(Collectors.toList())));
    }

    /**
     * 根据会员名称，分页查询上级会员列表
     *
     * @param headers      Http头部信息
     * @param pageByNameVO 接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<PageData<MemberManageQueryVO>> pageUpperMember(HttpHeaders headers, MemberManagePageByNameVO pageByNameVO) {
        UserLoginCacheDTO loginUser = memberCacheService.needLoginFromBusinessPlatform(headers);

        Specification<MemberRelationDO> specification = (root, query, criteriaBuilder) -> {
            List<Predicate> list = new ArrayList<>();
            list.add(criteriaBuilder.equal(root.get("relType").as(Integer.class), MemberRelationTypeEnum.OTHER.getCode()));
            list.add(criteriaBuilder.equal(root.get("subMemberId").as(Long.class), loginUser.getMemberId()));
            list.add(criteriaBuilder.equal(root.get("subRoleId").as(Long.class), loginUser.getMemberRoleId()));
            list.add(criteriaBuilder.equal(root.get("verified").as(Integer.class), MemberValidateStatusEnum.VERIFY_PASSED.getCode()));
            list.add(criteriaBuilder.equal(root.get("status").as(Integer.class), MemberStatusEnum.NORMAL.getCode()));

            // 上级会员名称
            if (StringUtils.hasLength(pageByNameVO.getName())) {
                Join<Object, Object> memberJoin = root.join("member", JoinType.LEFT);
                list.add(criteriaBuilder.like(memberJoin.get("name").as(String.class), "%" + pageByNameVO.getName().trim() + "%"));
            }

            Predicate[] p = new Predicate[list.size()];
            return criteriaBuilder.and(list.toArray(p));
        };

        Pageable page = PageRequest.of(pageByNameVO.getCurrent() - 1, pageByNameVO.getPageSize(), Sort.by("id").ascending());
        Page<MemberRelationDO> pageList = relationRepository.findAll(specification, page);
        return Wrapper.success(new PageData<>(pageList.getTotalElements(), pageList.getContent().stream().map(relationDO -> {
            MemberManageQueryVO queryVO = new MemberManageQueryVO();
            queryVO.setId(relationDO.getId());
            queryVO.setMemberId(relationDO.getMemberId());
            queryVO.setName(relationDO.getMember().getName());
            queryVO.setMemberTypeName(MemberTypeEnum.getCodeMessage(relationDO.getRole().getMemberType().getTypeEnum()));
            queryVO.setLevel(relationDO.getLevelRight().getLevel());
            queryVO.setLevelTag(relationDO.getLevelRight().getLevelTag());
            queryVO.setRoleId(relationDO.getRoleId());
            queryVO.setRoleName(relationDO.getRole().getRoleName());
            return queryVO;
        }).collect(Collectors.toList())));
    }

    /**
     * “售后能力 - 提交换货申请单” - 选择供应会员
     *
     * @param headers      Http头部信息
     * @param pageByNameVO 接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<PageData<MemberManageQueryVO>> pageAfterSaleMember(HttpHeaders headers, MemberManagePageByNameVO pageByNameVO) {
        UserLoginCacheDTO loginUser = memberCacheService.needLoginFromBusinessPlatform(headers);
        Pageable page = PageRequest.of(pageByNameVO.getCurrent() - 1, pageByNameVO.getPageSize(), Sort.by("id").ascending());
        // step 1:调用查询站点是否有勾选【SAAS多租户部署】
        boolean flag = false;
        if (Objects.nonNull(loginUser.getSiteId())) {
            SiteIdDTO requestVO = new SiteIdDTO();
            requestVO.setSiteId(loginUser.getSiteId());
            Wrapper<Boolean> booleanWrapper = platformManageFeignService.enableMultiTenancy(requestVO);
            flag = Optional.ofNullable(booleanWrapper).map(Wrapper::getData).orElse(false);
        }



        Specification<MemberRelationDO> specification;
        // 当前会员的【会员类型】是【企业会员】或【个人会员】且【会员角色类型】是【服务消费】且【PAAS-站点管理】有勾选【SAAS多租户部署】
        if ((loginUser.getMemberType().equals(MemberTypeEnum.MERCHANT.getCode()) || loginUser.getMemberType().equals(MemberTypeEnum.MERCHANT_PERSONAL.getCode()))&& flag) {
            // 会员数据来源于【会员能力--会员信息查询】中当前会员的上级会员且【会员类型】为【企业会员】或【个人会员】且【会员角色类型】为【服务提供】的会员数据
            specification = (root, query, criteriaBuilder) -> {
                List<Predicate> list = new ArrayList<>();
                // 排除 会员等级是平台会员
                list.add(criteriaBuilder.equal(root.get("relType").as(Integer.class), MemberRelationTypeEnum.OTHER.getCode()));
                list.add(criteriaBuilder.equal(root.get("verified").as(Integer.class), MemberValidateStatusEnum.VERIFY_PASSED.getCode()));

                list.add(criteriaBuilder.equal(root.get("status").as(Integer.class), MemberStatusEnum.NORMAL.getCode()));

                list.add(criteriaBuilder.equal(root.get("subMemberId").as(Long.class), loginUser.getMemberId()));
                list.add(criteriaBuilder.equal(root.get("subRoleId").as(Long.class), loginUser.getMemberRoleId()));
                // 【上级会员角色】
                Join<Object, Object> roleJoin = root.join("role", JoinType.LEFT);
                // 【会员角色类型】为【服务提供】
                list.add(criteriaBuilder.equal(roleJoin.get("roleType").get("typeEnum").as(Integer.class), RoleTypeEnum.SERVICE_PROVIDER.getCode()));
                // 【会员类型】为【企业会员】或【个人会员】等同 【会员等级类型】为【商户会员】
                list.add(criteriaBuilder.or(criteriaBuilder.equal(roleJoin.get("memberType").get("typeEnum").as(Integer.class), MemberTypeEnum.MERCHANT.getCode()), criteriaBuilder.equal(roleJoin.get("memberType").get("typeEnum").as(Integer.class), MemberTypeEnum.MERCHANT_PERSONAL.getCode())));
                list.add(criteriaBuilder.or(criteriaBuilder.equal(roleJoin.get("memberType").get("typeEnum").as(Integer.class), MemberTypeEnum.MERCHANT.getCode()), criteriaBuilder.equal(roleJoin.get("memberType").get("typeEnum").as(Integer.class), MemberTypeEnum.MERCHANT_PERSONAL.getCode())));

                // 上级会员名称
                if (StringUtils.hasLength(pageByNameVO.getName())) {
                    Join<Object, Object> memberJoin = root.join("member", JoinType.LEFT);
                    list.add(criteriaBuilder.like(memberJoin.get("name").as(String.class), "%" + pageByNameVO.getName().trim() + "%"));
                }
                return query.where(list.toArray(new Predicate[0])).getRestriction();
            };
            Page<MemberRelationDO> pageList = relationRepository.findAll(specification, page);
            return Wrapper.success(new PageData<>(pageList.getTotalElements(), pageList.getContent().stream().map(relationDO -> {
                MemberManageQueryVO queryVO = new MemberManageQueryVO();
                queryVO.setId(relationDO.getId());
                queryVO.setMemberId(relationDO.getMemberId());
                queryVO.setName(relationDO.getMember().getName());
                queryVO.setRoleId(relationDO.getRoleId());
                queryVO.setRoleName(relationDO.getRole().getRoleName());
                queryVO.setMemberTypeName(MemberTypeEnum.getCodeMessage(relationDO.getRole().getMemberType().getTypeEnum()));
                queryVO.setLevel(relationDO.getLevelRight().getLevel());
                queryVO.setLevelTag(relationDO.getLevelRight().getLevelTag());
                return queryVO;
            }).collect(Collectors.toList())));
        } else if ((loginUser.getMemberType().equals(MemberTypeEnum.MERCHANT.getCode()) || loginUser.getMemberType().equals(MemberTypeEnum.MERCHANT_PERSONAL.getCode())) && !flag) {
            specification = (root, query, criteriaBuilder) -> {
                List<Predicate> list = new ArrayList<>();
                list.add(criteriaBuilder.equal(root.get("verified").as(Integer.class), MemberValidateStatusEnum.VERIFY_PASSED.getCode()));
                list.add(criteriaBuilder.equal(root.get("status").as(Integer.class), MemberStatusEnum.NORMAL.getCode()));

                list.add(criteriaBuilder.equal(root.get("relType").as(Integer.class), MemberRelationTypeEnum.PLATFORM.getCode()));
                Join<Object, Object> subRoleJoin = root.join("subRole", JoinType.LEFT);
                list.add(criteriaBuilder.equal(subRoleJoin.get("roleType").get("typeEnum").as(Integer.class), RoleTypeEnum.SERVICE_PROVIDER.getCode()));
                list.add(criteriaBuilder.or(criteriaBuilder.equal(subRoleJoin.get("memberType").get("typeEnum").as(Integer.class), MemberTypeEnum.MERCHANT.getCode()), criteriaBuilder.equal(subRoleJoin.get("memberType").get("typeEnum").as(Integer.class), MemberTypeEnum.MERCHANT_PERSONAL.getCode())));

                // 平台会员名称
                if (StringUtils.hasLength(pageByNameVO.getName())) {
                    Join<Object, Object> subMemberJoin = root.join("subMember", JoinType.LEFT);
                    list.add(criteriaBuilder.like(subMemberJoin.get("name").as(String.class), "%" + pageByNameVO.getName().trim() + "%"));
                }

                Predicate[] p = new Predicate[list.size()];
                return criteriaBuilder.and(list.toArray(p));
            };

            Page<MemberRelationDO> pageList = relationRepository.findAll(specification, page);
            return Wrapper.success(new PageData<>(pageList.getTotalElements(), pageList.getContent().stream().map(relationDO -> {
                MemberManageQueryVO queryVO = new MemberManageQueryVO();
                queryVO.setId(relationDO.getId());
                queryVO.setMemberId(relationDO.getSubMemberId());
                queryVO.setName(relationDO.getSubMember().getName());
                queryVO.setRoleId(relationDO.getSubRoleId());
                queryVO.setRoleName(relationDO.getSubRole().getRoleName());
                queryVO.setMemberTypeName(MemberTypeEnum.getCodeMessage(relationDO.getSubRole().getMemberType().getTypeEnum()));
                queryVO.setLevel(relationDO.getLevelRight().getLevel());
                queryVO.setLevelTag(relationDO.getLevelRight().getLevelTag());
                return queryVO;
            }).collect(Collectors.toList())));
        } else {
            specification = (root, query, criteriaBuilder) -> {
                List<Predicate> list = new ArrayList<>();
                list.add(criteriaBuilder.equal(root.get("relType").as(Integer.class), MemberRelationTypeEnum.OTHER.getCode()));
                list.add(criteriaBuilder.equal(root.get("verified").as(Integer.class), MemberValidateStatusEnum.VERIFY_PASSED.getCode()));
                list.add(criteriaBuilder.equal(root.get("status").as(Integer.class), MemberStatusEnum.NORMAL.getCode()));

                list.add(criteriaBuilder.equal(root.get("subMemberId").as(Long.class), loginUser.getMemberId()));
                list.add(criteriaBuilder.equal(root.get("subRoleId").as(Long.class), loginUser.getMemberRoleId()));

                //上级会员角色
                Join<Object, Object> roleJoin = root.join("role", JoinType.LEFT);
                list.add(criteriaBuilder.or(criteriaBuilder.equal(roleJoin.get("memberType").get("typeEnum").as(Integer.class), MemberTypeEnum.CHANNEL.getCode()), criteriaBuilder.equal(roleJoin.get("memberType").get("typeEnum").as(Integer.class), MemberTypeEnum.CHANNEL_PERSONAL.getCode())));

                // 上级会员名称
                if (StringUtils.hasLength(pageByNameVO.getName())) {
                    Join<Object, Object> memberJoin = root.join("member", JoinType.LEFT);
                    list.add(criteriaBuilder.like(memberJoin.get("name").as(String.class), "%" + pageByNameVO.getName().trim() + "%"));
                }

                Predicate[] p = new Predicate[list.size()];
                return criteriaBuilder.and(list.toArray(p));
            };

            Page<MemberRelationDO> pageList = relationRepository.findAll(specification, page);
            return Wrapper.success(new PageData<>(pageList.getTotalElements(), pageList.getContent().stream().map(relationDO -> {
                MemberManageQueryVO queryVO = new MemberManageQueryVO();
                queryVO.setId(relationDO.getId());
                queryVO.setMemberId(relationDO.getMemberId());
                queryVO.setName(relationDO.getMember().getName());
                queryVO.setRoleId(relationDO.getRoleId());
                queryVO.setRoleName(relationDO.getRole().getRoleName());
                queryVO.setMemberTypeName(MemberTypeEnum.getCodeMessage(relationDO.getRole().getMemberType().getTypeEnum()));
                queryVO.setLevel(relationDO.getLevelRight().getLevel());
                queryVO.setLevelTag(relationDO.getLevelRight().getLevelTag());
                return queryVO;
            }).collect(Collectors.toList())));
        }
    }

    /**
     * “物流能力 - 新增物流公司” - 选择物流服务商
     *
     * @param headers Http头部信息
     * @param pageVO  接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<PageData<MemberManageQueryVO>> pageLogisticSubMember(HttpHeaders headers, MemberManagePageLogisticsVO pageVO) {
        UserLoginCacheDTO loginUser = memberCacheService.needLoginFromBusinessPlatform(headers);

        Specification<MemberRelationDO> specification = (root, query, criteriaBuilder) -> {
            List<Predicate> list = new ArrayList<>();
            list.add(criteriaBuilder.equal(root.get("memberId").as(Long.class), loginUser.getMemberId()));
            list.add(criteriaBuilder.equal(root.get("roleId").as(Long.class), loginUser.getMemberRoleId()));
            list.add(criteriaBuilder.equal(root.get("verified").as(Integer.class), MemberValidateStatusEnum.VERIFY_PASSED.getCode()));
            list.add(criteriaBuilder.equal(root.get("status").as(Integer.class), MemberStatusEnum.NORMAL.getCode()));

            //服务提供者
            Join<Object, Object> subRoleJoin = root.join("subRole", JoinType.LEFT);
            list.add(criteriaBuilder.equal(subRoleJoin.get("roleType").get("typeEnum").as(Integer.class), RoleTypeEnum.SERVICE_PROVIDER.getCode()));

            //会员名称
            if (StringUtils.hasLength(pageVO.getName())) {
                Join<Object, Object> subMemberJoin = root.join("subMember", JoinType.LEFT);
                list.add(criteriaBuilder.like(subMemberJoin.get("name").as(String.class), "%" + pageVO.getName().trim() + "%"));
            }

            if (pageVO.getRoleId() != null && !pageVO.getRoleId().equals(0L)) {
                list.add(criteriaBuilder.equal(root.get("subRoleId").as(Long.class), pageVO.getRoleId()));
            }

            Predicate[] p = new Predicate[list.size()];
            return criteriaBuilder.and(list.toArray(p));
        };

        List<MemberRelationDO> relationDOList = relationRepository.findAll(specification, Sort.by("id").ascending());

        if (!CollectionUtils.isEmpty(pageVO.getExcludeList())) {
            relationDOList = relationDOList.stream().filter(r -> pageVO.getExcludeList().stream().noneMatch(memberExcludeVO -> memberExcludeVO.getMemberId().equals(r.getSubMemberId()) && memberExcludeVO.getRoleId().equals(r.getSubRoleId()))).collect(Collectors.toList());
        }

        int totalCount = relationDOList.size();
        List<MemberRelationDO> pageList = CollectionPageUtil.pageList(relationDOList, totalCount, pageVO.getCurrent(), pageVO.getPageSize());

        return Wrapper.success(new PageData<>((long) totalCount, pageList.stream().map(p -> {
            MemberManageQueryVO queryVO = new MemberManageQueryVO();
            queryVO.setId(p.getId());
            queryVO.setMemberId(p.getSubMemberId());
            queryVO.setName(p.getSubMember().getName());
            queryVO.setRoleId(p.getSubRoleId());
            queryVO.setRoleName(p.getSubRole().getRoleName());
            queryVO.setMemberTypeName(MemberTypeEnum.getCodeMessage(p.getSubRole().getMemberType().getTypeEnum()));
            queryVO.setLevel(p.getLevelRight().getLevel());
            queryVO.setLevelTag(p.getLevelRight().getLevelTag());
            return queryVO;
        }).collect(Collectors.toList())));
    }

    /**
     * 分页查询会员下属用户
     *
     * @param headers Http头部新
     * @param pageVO  接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<PageData<UserQueryVO>> pageUsers(HttpHeaders headers, UserPageVO pageVO) {
        UserLoginCacheDTO loginUser = memberCacheService.checkUserFromCache(headers);
        return baseUserDetailService.pageUsers(loginUser.getMemberId(), pageVO.getName(), pageVO.getOrgName(), pageVO.getJobTitle(), pageVO.getCurrent(), pageVO.getPageSize(), true);
    }

    /**
     * "适用会员等级", 查询等级配置详情
     * @param headers Http头部信息
     * @param pageVO 接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<PageData<MemberSuitableLevelConfigVO>> pageMarketingSuitableLevelConfig(HttpHeaders headers, MemberLevelDetailPageVO pageVO) {
        UserLoginCacheDTO loginUser = memberCacheService.checkUserFromCache(headers);
        //当前会员的会员类型是企业会员或个人会员且会员角色类型是服务提供时，数据来源于当前会员的会员能力--会员规则配置--会员等级管理中且会员等级类型为商户会员且会员角色类型为服务消费的会员等级数据
        //当前会员的会员类型是渠道企业会员或渠道个人会员且会员角色类型是服务提供时，数据来源于当前会员的会员能力--会员规则配置--会员等级管理中且会员等级类型为渠道会员且会员角色类型为服务消费的会员等级数据
        if(!loginUser.getMemberRoleType().equals(RoleTypeEnum.SERVICE_PROVIDER.getCode())) {
            return Wrapper.success(new PageData<>(0L , new ArrayList<>()));
        }

        QMemberLevelConfigDO qMemberLevelConfig = QMemberLevelConfigDO.memberLevelConfigDO;
        QRoleDO qRole = QRoleDO.roleDO;

        JPAQuery<MemberSuitableLevelConfigVO> query = jpaQueryFactory.select(Projections.constructor(MemberSuitableLevelConfigVO.class, qMemberLevelConfig.id, qRole.memberType.typeEnum, qMemberLevelConfig.subRoleId, qRole.roleType.typeEnum, qRole.roleName, qMemberLevelConfig.levelType, qMemberLevelConfig.level, qMemberLevelConfig.levelTag))
                .from(qMemberLevelConfig).leftJoin(qRole).on(qMemberLevelConfig.subRoleId.eq(qRole.id))
                .where(qMemberLevelConfig.memberId.eq(loginUser.getMemberId()).and(qMemberLevelConfig.roleId.eq(loginUser.getMemberRoleId())).and(qMemberLevelConfig.levelType.eq(loginUser.getMemberLevelType())))
                .where(qRole.roleType.typeEnum.eq(RoleTypeEnum.SERVICE_CONSUMER.getCode()))
                .limit(pageVO.getPageSize()).offset(pageVO.getCurrentOffset());

        if(StringUtils.hasLength(pageVO.getMemberTypes())) {
            List<Integer> memberTypes = Stream.of(pageVO.getMemberTypes().split(","))
                    .filter(StringUtils::hasText)
                    .map(String::trim)
                    .map(Integer::valueOf)
                    .collect(Collectors.toList());
            query.where(qRole.memberType.typeEnum.in(memberTypes));
        }

        return Wrapper.success(new PageData<>(query.fetchCount(), query.fetch()));
    }

    /**
     * “营销能力” - 获取适用会员查询条件
     * @param headers Http头部信息
     * @return 查询结果
     */
    @Override
    public Wrapper<MemberSuitableConditionVO> getMarketingSuitableCondition(HttpHeaders headers, SuitableMemberTypeVO typeVO) {
        UserLoginCacheDTO loginUser = memberCacheService.needLoginFromBusinessPlatform(headers);

        MemberSuitableConditionVO conditionVO = new MemberSuitableConditionVO();
        // 会员类型（这里返回的是Id）
        List<MemberTypeIdAndNameVO> memberTypeList = baseMemberValidateService.getSubMemberTypeList(loginUser.getMemberType());
        memberTypeList.add(0, new MemberTypeIdAndNameVO(0L, MemberStringEnum.ALL.getName()));
        conditionVO.setMemberTypes(memberTypeList);

        // 会员等级
        List<LevelAndTagVO> levelList = baseMemberLevelConfigService.listSubMemberLevels(loginUser.getMemberId(), loginUser.getMemberRoleId());
        levelList.add(0, new LevelAndTagVO(0, MemberStringEnum.ALL.getName()));
        conditionVO.setLevels(levelList);

        // 适用新老用户
        List<SelectItemVO> suitableMemberTypes = Optional.ofNullable(typeVO).map(SuitableMemberTypeVO::getSuitableMemberTypes).map(memberTypes -> memberTypes.stream().map(e -> {
            AbilitySuitableMemberEnum abilitySuitableMemberEnum = AbilitySuitableMemberEnum.toEnum(e);
            return new SelectItemVO(abilitySuitableMemberEnum.getCode(), abilitySuitableMemberEnum.getMessage());
        }).collect(Collectors.toList())).orElse(new ArrayList<>());
        suitableMemberTypes.add(0, new SelectItemVO(0, MemberStringEnum.ALL.getName()));
        conditionVO.setSuitableMemberTypes(suitableMemberTypes);

        return Wrapper.success(conditionVO);
    }

    /**
     * “平台营销” - 获取适用会员查询条件
     * @param headers Http头部信息
     * @param typeVO 接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<PlatformMemberSuitableConditionVO> getPlatformMarketingSuitableCondition(HttpHeaders headers, PlatformSuitableMemberTypeVO typeVO) {
        UserLoginCacheDTO loginUser = memberCacheService.needLoginFromManagePlatform(headers);

        PlatformMemberSuitableConditionVO conditionVO = new PlatformMemberSuitableConditionVO();

        // 会员类型(这里是memberTypeEnum)
//        List<SelectItemVO> memberTypeList = Optional.ofNullable(typeVO).map(PlatformSuitableMemberTypeVO::getMemberTypes).map(memberTypes -> memberTypes.stream().map(type -> {
//            MemberTypeEnum memberTypeEnum = MemberTypeEnum.toEnum(type);
//            return new SelectItemVO(memberTypeEnum.getCode(), memberTypeEnum.getMessage());
//        }).collect(Collectors.toList())).orElse(new ArrayList<>());

        List<SelectItemVO> memberTypeList = Stream.of(MemberTypeEnum.MERCHANT, MemberTypeEnum.MERCHANT_PERSONAL).map(e -> new SelectItemVO(e.getCode(), e.getMessage())).collect(Collectors.toList());
        memberTypeList.add(0, new SelectItemVO(0, MemberStringEnum.ALL.getName()));
        conditionVO.setMemberTypes(memberTypeList);

        //会员等级
        List<LevelAndTagVO> levelList = baseMemberLevelConfigService.listSubMemberLevels(loginUser.getMemberId(), loginUser.getMemberRoleId());
        levelList.add(0, new LevelAndTagVO(0, MemberStringEnum.ALL.getName()));
        conditionVO.setLevels(levelList);

        // 适用新老会员
//        List<SelectItemVO> suitableMemberTypes = Optional.ofNullable(typeVO).map(PlatformSuitableMemberTypeVO::getSuitableMemberTypes).map(memberTypes -> memberTypes.stream().map(e -> {
//            PlatformSuitableMemberEnum suitableMemberTypeEnum = PlatformSuitableMemberEnum.toEnum(e);
//            return new SelectItemVO(suitableMemberTypeEnum.getCode(), suitableMemberTypeEnum.getMessage());
//        }).collect(Collectors.toList())).orElse(new ArrayList<>());
        List<SelectItemVO> suitableMemberTypes = Arrays.stream(PlatformSuitableMemberEnum.values()).map(e -> new SelectItemVO(e.getCode(), e.getMessage())).collect(Collectors.toList());
        suitableMemberTypes.add(0, new SelectItemVO(0, MemberStringEnum.ALL.getName()));
        conditionVO.setSuitableMemberTypes(suitableMemberTypes);

        return Wrapper.success(conditionVO);
    }

    /**
     * “营销能力” - 查询适用会员(分页)
     * @param headers Http头部信息
     * @param pageVO 接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<PageData<MemberSuitableVO>> pageMarketingSuitable(HttpHeaders headers, MarketingSuitablePageVO pageVO) {
        UserLoginCacheDTO loginUser = memberCacheService.needLoginFromBusinessPlatform(headers);

        Specification<MemberRelationDO> specification = (root, query, criteriaBuilder) -> {
            List<Predicate> list = new ArrayList<>();
            list.add(criteriaBuilder.equal(root.get("memberId").as(Long.class), loginUser.getMemberId()));
            list.add(criteriaBuilder.equal(root.get("roleId").as(Long.class), loginUser.getMemberRoleId()));
            list.add(criteriaBuilder.equal(root.get("status").as(Integer.class), MemberStatusEnum.NORMAL.getCode()));
            // 会员已入库
            list.add(criteriaBuilder.equal(root.get("verified").as(Integer.class), MemberValidateStatusEnum.VERIFY_PASSED.getCode()));

            // 服务消费者
            list.add(criteriaBuilder.equal(root.get("subRole").get("roleType").get("typeEnum").as(Integer.class), RoleTypeEnum.SERVICE_CONSUMER.getCode()));

            // 根据会员等级id
            if(!CollectionUtils.isEmpty(pageVO.getSuitableMemberLevelTypes())) {
                list.add(root.get("levelRight").get("levelConfig").get("id").in(pageVO.getSuitableMemberLevelTypes()));
            }

            if (NumberUtil.notNullOrZero(pageVO.getMemberId())) {
                list.add(criteriaBuilder.equal(root.get("subMemberId").as(Long.class), pageVO.getMemberId()));
            }

            if (StringUtils.hasLength(pageVO.getName())) {
                list.add(criteriaBuilder.like(root.get("subMember").get("name").as(String.class), "%" + pageVO.getName() + "%"));
            }

            if (NumberUtil.notNullOrZero(pageVO.getMemberTypeEnum())) {
                list.add(criteriaBuilder.equal(root.get("subRole").get("memberType").get("typeEnum").as(Integer.class), pageVO.getMemberTypeEnum()));
            }

            if (NumberUtil.notNullOrZero(pageVO.getLevel())) {
                list.add(criteriaBuilder.equal(root.get("levelRight").get("level").as(Integer.class), pageVO.getLevel()));
            }

            if (NumberUtil.notNullOrZero(pageVO.getSuitableMemberType())) {
                if (AbilitySuitableMemberEnum.NEW_MEMBER.getCode().equals(pageVO.getSuitableMemberType())) {
                    list.add(criteriaBuilder.greaterThanOrEqualTo(root.get("depositTime").as(LocalDateTime.class), DateTimeUtil.getToday()));
                } else {
                    list.add(criteriaBuilder.lessThan(root.get("depositTime").as(LocalDateTime.class), DateTimeUtil.getToday()));
                }
            }

            if (Objects.nonNull(pageVO.getBecomeTimeStart())) {
                LocalDateTime startDate = DateTimeUtil.parseDateTime(pageVO.getBecomeTimeStart());
                list.add(criteriaBuilder.greaterThanOrEqualTo(root.get("depositTime"), startDate));
            }

            if (Objects.nonNull(pageVO.getBecomeTimeEnd())) {
                LocalDateTime endDate = DateTimeUtil.parseDateTime(pageVO.getBecomeTimeEnd());
                list.add(criteriaBuilder.lessThanOrEqualTo(root.get("depositTime"), endDate));
            }

            if(!CollectionUtils.isEmpty(pageVO.getExcludeMemberList())) {
                List<Predicate> excludeList = pageVO.getExcludeMemberList().stream().map(ex -> criteriaBuilder.and(criteriaBuilder.notEqual(root.get("subMemberId").as(Long.class), ex.getMemberId()), criteriaBuilder.notEqual(root.get("subRoleId").as(Long.class), ex.getRoleId()))).collect(Collectors.toList());
                list.addAll(excludeList);
            }

            Predicate[] p = new Predicate[list.size()];
            return criteriaBuilder.and(list.toArray(p));
        };

        Pageable pageable = PageRequest.of(pageVO.getCurrent() - 1, pageVO.getPageSize(), Sort.by("id").descending());

        Page<MemberRelationDO> pageList = relationRepository.findAll(specification, pageable);
        return Wrapper.success(new PageData<>(pageList.getTotalElements(), pageList.getContent().stream().map(relationDO -> {
            MemberSuitableVO queryVO = new MemberSuitableVO();
            queryVO.setId(relationDO.getId());
            queryVO.setMemberId(relationDO.getSubMemberId());
            queryVO.setRoleId(relationDO.getSubRoleId());
            queryVO.setName(relationDO.getSubMember().getName());
            // 适用会员类型
            AbilitySuitableMemberEnum abilitySuitableMemberEnum = Optional.ofNullable(relationDO.getDepositTime())
                    .map(depositTime -> depositTime.isBefore(DateTimeUtil.getToday()) ? AbilitySuitableMemberEnum.NEW_MEMBER : AbilitySuitableMemberEnum.OLD_MEMBER)
                    .orElse(null);
            queryVO.setSuitableMemberType(Objects.isNull(abilitySuitableMemberEnum) ? 0 : abilitySuitableMemberEnum.getCode());
            queryVO.setSuitableMemberTypeName(Objects.isNull(abilitySuitableMemberEnum) ? "" : abilitySuitableMemberEnum.getMessage());
            queryVO.setRoleName(relationDO.getSubRoleName());
            queryVO.setLevelTag(relationDO.getLevelRight() == null ? "" : relationDO.getLevelRight().getLevelTag());
            queryVO.setMemberTypeName(MemberTypeEnum.getCodeMessage(relationDO.getSubRole().getMemberType().getTypeEnum()));
            queryVO.setBecomeTime(DateTimeUtil.formatDateTime(relationDO.getDepositTime()));
            return queryVO;
        }).collect(Collectors.toList())));
    }

    /**
     * “平台营销” - 查询适用会员(分页)
     * @param headers Http头部信息
     * @param pageVO 接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<PageData<MemberSuitableVO>> pagePlatformMarketingSuitable(HttpHeaders headers, MarketingSuitablePageVO pageVO) {
        UserLoginCacheDTO loginUser = memberCacheService.needLoginFromManagePlatform(headers);

        Specification<MemberRelationDO> specification = (root, query, criteriaBuilder) -> {
            List<Predicate> list = new ArrayList<>();
            list.add(criteriaBuilder.equal(root.get("relType").as(Integer.class), MemberRelationTypeEnum.PLATFORM.getCode()));
            list.add(criteriaBuilder.equal(root.get("status").as(Integer.class), MemberStatusEnum.NORMAL.getCode()));
            // 会员已入库
            list.add(criteriaBuilder.equal(root.get("verified").as(Integer.class), MemberValidateStatusEnum.VERIFY_PASSED.getCode()));

            // 服务消费者
            list.add(criteriaBuilder.equal(root.get("subRole").get("roleType").get("typeEnum").as(Integer.class), RoleTypeEnum.SERVICE_CONSUMER.getCode()));

            // 根据会员等级id
            if(!CollectionUtils.isEmpty(pageVO.getSuitableMemberLevelTypes())) {
                list.add(root.get("levelRight").get("levelConfig").get("id").in(pageVO.getSuitableMemberLevelTypes()));
            }

            if (NumberUtil.notNullOrZero(pageVO.getMemberId())) {
                list.add(criteriaBuilder.equal(root.get("subMemberId").as(Long.class), pageVO.getMemberId()));
            }

            if (StringUtils.hasLength(pageVO.getName())) {
                list.add(criteriaBuilder.like(root.get("subMember").get("name").as(String.class), "%" + pageVO.getName() + "%"));
            }

            if (NumberUtil.notNullOrZero(pageVO.getMemberTypeEnum())) {
                list.add(criteriaBuilder.equal(root.get("subRole").get("memberType").get("typeEnum").as(Integer.class), pageVO.getMemberTypeEnum()));
            }

            if (NumberUtil.notNullOrZero(pageVO.getLevel())) {
                list.add(criteriaBuilder.equal(root.get("levelRight").get("level").as(Integer.class), pageVO.getLevel()));
            }

            if (NumberUtil.notNullOrZero(pageVO.getSuitableMemberType())) {
                if (AbilitySuitableMemberEnum.NEW_MEMBER.getCode().equals(pageVO.getSuitableMemberType())) {
                    list.add(criteriaBuilder.greaterThanOrEqualTo(root.get("depositTime").as(LocalDateTime.class), DateTimeUtil.getToday()));
                } else {
                    list.add(criteriaBuilder.lessThan(root.get("depositTime").as(LocalDateTime.class), DateTimeUtil.getToday()));
                }
            }

            if (Objects.nonNull(pageVO.getBecomeTimeStart())) {
                LocalDateTime startDate = DateTimeUtil.parseDateTime(pageVO.getBecomeTimeStart());
                list.add(criteriaBuilder.greaterThanOrEqualTo(root.get("depositTime"), startDate));
            }

            if (Objects.nonNull(pageVO.getBecomeTimeEnd())) {
                LocalDateTime endDate = DateTimeUtil.parseDateTime(pageVO.getBecomeTimeEnd());
                list.add(criteriaBuilder.lessThanOrEqualTo(root.get("depositTime"), endDate));
            }

            if(!CollectionUtils.isEmpty(pageVO.getExcludeMemberList())) {
                List<Predicate> orList = pageVO.getExcludeMemberList().stream().map(ex -> criteriaBuilder.and(criteriaBuilder.notEqual(root.get("subMemberId").as(Long.class), ex.getMemberId()), criteriaBuilder.notEqual(root.get("subRoleId").as(Long.class), ex.getRoleId()))).collect(Collectors.toList());
                Predicate[] orP = new Predicate[orList.size()];
                list.add(criteriaBuilder.or(orList.toArray(orP)));
            }

            Predicate[] p = new Predicate[list.size()];
            return criteriaBuilder.and(list.toArray(p));
        };

        Pageable pageable = PageRequest.of(pageVO.getCurrent() - 1, pageVO.getPageSize(), Sort.by("id").descending());

        Page<MemberRelationDO> pageList = relationRepository.findAll(specification, pageable);
        return Wrapper.success(new PageData<>(pageList.getTotalElements(), pageList.getContent().stream().map(relationDO -> {
            MemberSuitableVO queryVO = new MemberSuitableVO();
            queryVO.setId(relationDO.getId());
            queryVO.setMemberId(relationDO.getSubMemberId());
            queryVO.setRoleId(relationDO.getSubRoleId());
            queryVO.setName(relationDO.getSubMember().getName());
            // 适用会员类型
            AbilitySuitableMemberEnum abilitySuitableMemberEnum = Optional.ofNullable(relationDO.getDepositTime())
                    .map(depositTime -> depositTime.isBefore(DateTimeUtil.getToday()) ? AbilitySuitableMemberEnum.NEW_MEMBER : AbilitySuitableMemberEnum.OLD_MEMBER)
                    .orElse(null);
            queryVO.setSuitableMemberType(Objects.isNull(abilitySuitableMemberEnum) ? 0 : abilitySuitableMemberEnum.getCode());
            queryVO.setSuitableMemberTypeName(Objects.isNull(abilitySuitableMemberEnum) ? "" : abilitySuitableMemberEnum.getMessage());
            queryVO.setRoleName(relationDO.getSubRoleName());
            queryVO.setLevelTag(relationDO.getLevelRight() == null ? "" : relationDO.getLevelRight().getLevelTag());
            queryVO.setMemberTypeName(MemberTypeEnum.getCodeMessage(relationDO.getSubRole().getMemberType().getTypeEnum()));
            queryVO.setBecomeTime(DateTimeUtil.formatDateTime(relationDO.getDepositTime()));
            return queryVO;
        }).collect(Collectors.toList())));
    }

    /**
     * “平台营销” - 获取邀请报名参加会员查询条件
     * @param headers Http头部信息
     * @return 查询结果
     */
    @Override
    public Wrapper<PlatformMemberInviteConditionVO> getPlatformMarketingInviteCondition(HttpHeaders headers) {
        UserLoginCacheDTO loginUser = memberCacheService.needLoginFromManagePlatform(headers);

        PlatformMemberInviteConditionVO conditionVO = new PlatformMemberInviteConditionVO();

        // 会员类型
        List<SelectItemVO> memberTypeList = Stream.of(MemberTypeEnum.MERCHANT, MemberTypeEnum.MERCHANT_PERSONAL)
                .map(type -> new SelectItemVO(type.getCode(), type.getMessage()))
                .collect(Collectors.toList());
        memberTypeList.add(0, new SelectItemVO(0, MemberStringEnum.ALL.getName()));
        conditionVO.setMemberTypes(memberTypeList);

        //会员等级
        List<LevelAndTagVO> levelList = baseMemberLevelConfigService.listSubMemberLevels(loginUser.getMemberId(), loginUser.getMemberRoleId());
        levelList.add(0, new LevelAndTagVO(0, MemberStringEnum.ALL.getName()));
        conditionVO.setLevels(levelList);

        // 会员角色
        conditionVO.setRoles(baseMemberLevelConfigService.findLevelConfigRoles(loginUser.getMemberId(), loginUser.getMemberRoleId()));

        return Wrapper.success(conditionVO);
    }

    /**
     * “平台营销” - 查询邀请报名参加会员列表
     * @param headers Http头部信息
     * @param pageVO 接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<PageData<PlatformMarketingInvitePageVO>> pagePlatformMarketingInvite(HttpHeaders headers, PlatformMarketingInviteQueryVO pageVO) {
        UserLoginCacheDTO loginUser = memberCacheService.needLoginFromManagePlatform(headers);

        Specification<MemberRelationDO> specification = (root, query, criteriaBuilder) -> {
            List<Predicate> list = new ArrayList<>();
            list.add(criteriaBuilder.equal(root.get("relType").as(Long.class), MemberRelationTypeEnum.PLATFORM.getCode()));
            list.add(criteriaBuilder.equal(root.get("status").as(Integer.class), MemberStatusEnum.NORMAL.getCode()));
            // 会员审核通过
            list.add(criteriaBuilder.equal(root.get("verified").as(Integer.class), MemberValidateStatusEnum.VERIFY_PASSED.getCode()));

            // 服务提供者
            Join<MemberRelationDO, RoleDO> subRoleJoin = root.join("subRole", JoinType.LEFT);
            list.add(criteriaBuilder.equal(subRoleJoin.get("roleType").get("typeEnum").as(Integer.class), RoleTypeEnum.SERVICE_PROVIDER.getCode()));
            // 企业或个人
            List<Integer> memberTypeList = Arrays.asList(MemberTypeEnum.MERCHANT.getCode(), MemberTypeEnum.MERCHANT_PERSONAL.getCode());
            list.add(criteriaBuilder.and(subRoleJoin.get("memberType").get("typeEnum").as(Integer.class).in(memberTypeList)));

            if (StringUtils.hasLength(pageVO.getName())) {
                Join<MemberRelationDO, MemberDO> subMemberJoin = root.join("subMember", JoinType.LEFT);
                list.add(criteriaBuilder.like(subMemberJoin.get("name").as(String.class), "%" + pageVO.getName() + "%"));
            }

            if (NumberUtil.notNullOrZero(pageVO.getRoleId())) {
                list.add(criteriaBuilder.equal(root.get("subRoleId").as(Long.class), pageVO.getRoleId()));
            }

            if (NumberUtil.notNullOrZero(pageVO.getLevel())) {
                Join<MemberRelationDO, MemberLevelRightDO> levelRightJoin = root.join("levelRight", JoinType.LEFT);
                list.add(criteriaBuilder.equal(levelRightJoin.get("level").as(Integer.class), pageVO.getLevel()));
            }

            if(!CollectionUtils.isEmpty(pageVO.getExcludeMemberList())) {
                List<Predicate> orList = pageVO.getExcludeMemberList().stream().map(ex -> criteriaBuilder.and(criteriaBuilder.notEqual(root.get("subMemberId").as(Long.class), ex.getMemberId()), criteriaBuilder.notEqual(root.get("subRoleId").as(Long.class), ex.getRoleId()))).collect(Collectors.toList());
                Predicate[] orP = new Predicate[orList.size()];
                list.add(criteriaBuilder.or(orList.toArray(orP)));
            }

            Predicate[] p = new Predicate[list.size()];
            return criteriaBuilder.and(list.toArray(p));
        };

        Pageable pageable = PageRequest.of(pageVO.getCurrent() - 1, pageVO.getPageSize(), Sort.by("id").descending());
        Page<MemberRelationDO> pageList = relationRepository.findAll(specification, pageable);
        return Wrapper.success(new PageData<>(pageList.getTotalElements(), pageList.getContent().stream().map(relation -> {
            PlatformMarketingInvitePageVO invitePageVO = new PlatformMarketingInvitePageVO();
            invitePageVO.setId(relation.getId());
            invitePageVO.setMemberId(relation.getSubMemberId());
            invitePageVO.setRoleId(relation.getSubRoleId());
            invitePageVO.setName(relation.getSubMember().getName());
            invitePageVO.setRoleName(relation.getSubRoleName());
            invitePageVO.setMemberTypeName(MemberTypeEnum.getCodeMessage(relation.getSubRole().getMemberType().getTypeEnum()));
            invitePageVO.setLevel(relation.getLevelRight() == null ? 0 : relation.getLevelRight().getLevel());
            invitePageVO.setLevelTag(relation.getLevelRight() == null ? "" : relation.getLevelRight().getLevelTag());
            return invitePageVO;
        }).collect(Collectors.toList())));
    }

    /**
     * “订单服务 - 代客下单” - 查询角色为服务消费者的平台会员列表
     *
     * @param headers Http头部信息
     * @param nameVO  接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<List<MemberManageQueryVO>> findPlatformConsumerMembers(HttpHeaders headers, MemberManageNameVO nameVO) {
        UserLoginCacheDTO loginUser = memberCacheService.needLoginFromBusinessPlatform(headers);

        //如果输入name为空或当前登录会员角色类型不是服务提供者
        if (!StringUtils.hasText(nameVO.getName()) || !loginUser.getMemberRoleType().equals(RoleTypeEnum.SERVICE_PROVIDER.getCode())) {
            return Wrapper.success(new ArrayList<>());
        }

        // step 1:调用查询站点是否有勾选【SAAS多租户部署】
        boolean flag = false;
        if (Objects.nonNull(loginUser.getSiteId())) {
            SiteIdDTO requestVO = new SiteIdDTO();
            requestVO.setSiteId(loginUser.getSiteId());
            Wrapper<Boolean> booleanWrapper = platformManageFeignService.enableMultiTenancy(requestVO);
            flag = Optional.ofNullable(booleanWrapper).map(Wrapper::getData).orElse(false);
        }

        //通用筛选条件   如果后期需求又迭代了，这部分条件可以拆了放下面
        Specification<MemberRelationDO> specification = (root, query, criteriaBuilder) -> {
            List<Predicate> list = new ArrayList<>();
            list.add(criteriaBuilder.equal(root.get("memberId").as(Long.class), loginUser.getMemberId()));
            list.add(criteriaBuilder.equal(root.get("roleId").as(Long.class), loginUser.getMemberRoleId()));
            list.add(criteriaBuilder.equal(root.get("relType").as(Long.class), MemberRelationTypeEnum.OTHER.getCode()));
            list.add(criteriaBuilder.equal(root.get("status").as(Integer.class), MemberStatusEnum.NORMAL.getCode()));
            list.add(criteriaBuilder.equal(root.get("verified").as(Integer.class), MemberValidateStatusEnum.VERIFY_PASSED.getCode()));

            if (StringUtils.hasText(nameVO.getName())) {
                Join<MemberRelationDO, MemberDO> subMemberJoin = root.join("subMember", JoinType.LEFT);
                list.add(criteriaBuilder.like(subMemberJoin.get("name").as(String.class), "%" + nameVO.getName().trim() + "%"));
            }

            Join<MemberRelationDO, RoleDO> subRoleJoin = root.join("subRole", JoinType.LEFT);
            //会员角色类型为服务消费者
            list.add(criteriaBuilder.equal(subRoleJoin.get("roleType").get("typeEnum").as(Integer.class), RoleTypeEnum.SERVICE_CONSUMER.getCode()));

            Predicate[] p = new Predicate[list.size()];
            return criteriaBuilder.and(list.toArray(p));
        };

        //当前会员的会员类型是企业会员或个人会员且会员角色类型是服务提供且PAAS-站点管理有勾选SAAS多租户部署
        if ((loginUser.getMemberType().equals(MemberTypeEnum.MERCHANT.getCode()) || loginUser.getMemberType().equals(MemberTypeEnum.MERCHANT_PERSONAL.getCode())) && flag) {
            specification = specification.and((root, query, criteriaBuilder) -> {
                List<Predicate> list = new ArrayList<>();
                Join<MemberRelationDO, RoleDO> subRoleJoin = root.join("subRole", JoinType.LEFT);
                //下级会员类型是企业会员或个人会员
                list.add(criteriaBuilder.or(criteriaBuilder.equal(subRoleJoin.get("memberType").get("typeEnum").as(Integer.class), MemberTypeEnum.MERCHANT.getCode()), criteriaBuilder.equal(subRoleJoin.get("memberType").get("typeEnum").as(Integer.class), MemberTypeEnum.MERCHANT_PERSONAL.getCode())));
                return criteriaBuilder.and(list.toArray(new Predicate[0]));
            });
        } else if ((loginUser.getMemberType().equals(MemberTypeEnum.MERCHANT.getCode()) || loginUser.getMemberType().equals(MemberTypeEnum.MERCHANT_PERSONAL.getCode()))) {
            //当前会员的会员类型是企业会员或个人会员且会员角色类型是服务提供者
            specification = specification.and((root, query, criteriaBuilder) -> {
                List<Predicate> list = new ArrayList<>();
                Join<MemberRelationDO, RoleDO> subRoleJoin = root.join("subRole", JoinType.LEFT);
                //下级会员类型是企业会员或个人会员
                list.add(criteriaBuilder.or(criteriaBuilder.equal(subRoleJoin.get("memberType").get("typeEnum").as(Integer.class), MemberTypeEnum.MERCHANT.getCode()), criteriaBuilder.equal(subRoleJoin.get("memberType").get("typeEnum").as(Integer.class), MemberTypeEnum.MERCHANT_PERSONAL.getCode())));
                return criteriaBuilder.and(list.toArray(new Predicate[0]));
            });
        } else if ((loginUser.getMemberType().equals(MemberTypeEnum.CHANNEL.getCode()) || loginUser.getMemberType().equals(MemberTypeEnum.CHANNEL_PERSONAL.getCode()))) {
            //当前会员的会员类型是渠道企业会员或渠道个人会员且会员角色类型是服务提供者
            specification = specification.and((root, query, criteriaBuilder) -> {
                List<Predicate> list = new ArrayList<>();
                Join<MemberRelationDO, RoleDO> subRoleJoin = root.join("subRole", JoinType.LEFT);
                //下级会员类型是是渠道企业会员或渠道个人会员
                list.add(criteriaBuilder.or(criteriaBuilder.equal(subRoleJoin.get("memberType").get("typeEnum").as(Integer.class), MemberTypeEnum.CHANNEL.getCode()), criteriaBuilder.equal(subRoleJoin.get("memberType").get("typeEnum").as(Integer.class), MemberTypeEnum.CHANNEL_PERSONAL.getCode())));
                return criteriaBuilder.and(list.toArray(new Predicate[0]));
            });
        } else {
            specification = null;
        }

        Pageable pageable = PageRequest.of(0, 30, Sort.by("id").ascending());
        return Wrapper.success(relationRepository.findAll(specification, pageable).getContent().stream().map(relationDO -> {
            MemberManageQueryVO queryVO = new MemberManageQueryVO();
            queryVO.setId(relationDO.getId());
            queryVO.setMemberId(relationDO.getSubMemberId());
            queryVO.setName(relationDO.getSubMember().getName());
            queryVO.setRoleId(relationDO.getSubRoleId());
            queryVO.setRoleName(relationDO.getSubRoleName());
            queryVO.setMemberTypeName(MemberTypeEnum.getCodeMessage(relationDO.getSubRole().getMemberType().getTypeEnum()));
            queryVO.setLevel(relationDO.getLevelRight().getLevel());
            queryVO.setLevelTag(relationDO.getLevelRight().getLevelTag());
            return queryVO;
        }).collect(Collectors.toList()));
    }

    /**
     * “订单服务 - 新增现货采购订单” - 查询供应会员列表
     *
     * @param headers Http头部信息
     * @param pageVO  接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<PageData<MemberManageQueryVO>> pageBuyerOrderMembers(HttpHeaders headers, MemberManagePageByNameVO pageVO) {
        UserLoginCacheDTO loginUser = memberCacheService.needLoginFromBusinessPlatform(headers);

        //如果当前登录会员角色类型不是服务消费者
        if (!loginUser.getMemberRoleType().equals(RoleTypeEnum.SERVICE_CONSUMER.getCode())) {
            return Wrapper.success(new PageData<>(0L, new ArrayList<>()));
        }

        // step 1:调用查询站点是否有勾选【SAAS多租户部署】
        Boolean isEnableMultiTenancy = siteService.isEnableMultiTenancy(headers).getData();

        Specification<MemberRelationDO> specification;

        //如果会员类型是企业会员或个人会员且会员角色类型是服务消费且【PAAS-站点管理】有勾选【SAAS多租户部署】
        //企业会员或个人会员这个条件等价于会员等级类型为商户会员
        if (loginUser.getMemberLevelType().equals(MemberLevelTypeEnum.MERCHANT.getCode()) && isEnableMultiTenancy) {
            specification = (root, query, criteriaBuilder) -> {
                List<Predicate> list = new ArrayList<>();
                list.add(criteriaBuilder.equal(root.get("relType").as(Integer.class), MemberRelationTypeEnum.OTHER.getCode()));
                list.add(criteriaBuilder.equal(root.get("subMemberId").as(Long.class), loginUser.getMemberId()));
                list.add(criteriaBuilder.equal(root.get("subRoleId").as(Long.class), loginUser.getMemberRoleId()));
                list.add(criteriaBuilder.equal(root.get("verified").as(Integer.class), MemberValidateStatusEnum.VERIFY_PASSED.getCode()));
                list.add(criteriaBuilder.equal(root.get("status").as(Integer.class), MemberStatusEnum.NORMAL.getCode()));

                //上级会员角色为服务提供者且会员类型为企业会员或个人会员
                Join<Object, Object> roleJoin = root.join("role", JoinType.LEFT);
                list.add(criteriaBuilder.equal(roleJoin.get("roleType").get("typeEnum").as(Integer.class), RoleTypeEnum.SERVICE_PROVIDER.getCode()));
                list.add(criteriaBuilder.or(criteriaBuilder.equal(roleJoin.get("memberType").get("typeEnum").as(Integer.class), MemberTypeEnum.MERCHANT.getCode()), criteriaBuilder.equal(roleJoin.get("memberType").get("typeEnum").as(Integer.class), MemberTypeEnum.MERCHANT_PERSONAL.getCode())));

                // 上级会员名称
                if (StringUtils.hasLength(pageVO.getName())) {
                    Join<Object, Object> memberJoin = root.join("member", JoinType.LEFT);
                    list.add(criteriaBuilder.like(memberJoin.get("name").as(String.class), "%" + pageVO.getName().trim() + "%"));
                }

                Predicate[] p = new Predicate[list.size()];
                return criteriaBuilder.and(list.toArray(p));
            };
        } else {
            //当前会员的会员类型是企业会员或个人会员且会员角色类型是服务消费时，会员数据来源于【平台后台--会员管理--会员维护】中会员类型为企业会员或个人会员且会员角色类型为服务提供的会员数据
            //当前会员的会员类型是渠道企业会员或渠道个人会员且会员角色类型是服务消费时，会员数据来源于会员能力--会员信息查询中当前渠道会员的上级渠道会员且会员等级类型为渠道会员且会员角色类型为服务提供
            specification = (root, query, criteriaBuilder) -> {
                List<Predicate> list = new ArrayList<>();
                if (loginUser.getMemberLevelType().equals(MemberLevelTypeEnum.MERCHANT.getCode())) {
                    list.add(criteriaBuilder.equal(root.get("relType").as(Integer.class), MemberRelationTypeEnum.PLATFORM.getCode()));
                    list.add(criteriaBuilder.equal(root.get("subRole").get("roleType").get("typeEnum").as(Integer.class), RoleTypeEnum.SERVICE_PROVIDER.getCode()));
                    list.add(criteriaBuilder.or(criteriaBuilder.equal(root.get("subRole").get("memberType").get("typeEnum").as(Integer.class), MemberTypeEnum.MERCHANT.getCode()), criteriaBuilder.equal(root.get("subRole").get("memberType").get("typeEnum").as(Integer.class), MemberTypeEnum.MERCHANT_PERSONAL.getCode())));

                    if (StringUtils.hasText(pageVO.getName())) {
                        list.add(criteriaBuilder.like(root.get("subMember").get("name").as(String.class), "%" + pageVO.getName().trim() + "%"));
                    }
                }

                if (loginUser.getMemberLevelType().equals(MemberLevelTypeEnum.CHANNEL.getCode())) {
                    list.add(criteriaBuilder.equal(root.get("subMemberId").as(Long.class), loginUser.getMemberId()));
                    list.add(criteriaBuilder.equal(root.get("subRoleId").as(Long.class), loginUser.getMemberRoleId()));
                    list.add(criteriaBuilder.equal(root.get("relType").as(Integer.class), MemberRelationTypeEnum.OTHER.getCode()));
                    list.add(criteriaBuilder.or(criteriaBuilder.equal(root.get("role").get("memberType").get("typeEnum").as(Integer.class), MemberTypeEnum.CHANNEL.getCode()), criteriaBuilder.equal(root.get("role").get("memberType").get("typeEnum").as(Integer.class), MemberTypeEnum.CHANNEL_PERSONAL.getCode())));
                    list.add(criteriaBuilder.equal(root.get("role").get("roleType").get("typeEnum").as(Integer.class),RoleTypeEnum.SERVICE_PROVIDER.getCode()));

                    if (StringUtils.hasText(pageVO.getName())) {
                        list.add(criteriaBuilder.like(root.get("member").get("name").as(String.class), "%" + pageVO.getName().trim() + "%"));
                    }
                }
                Predicate[] p = new Predicate[list.size()];
                return criteriaBuilder.and(list.toArray(p));
            };
        }

        Pageable pageable = PageRequest.of(pageVO.getCurrent() - 1, pageVO.getPageSize(), Sort.by("id").descending());
        Page<MemberRelationDO> pageList = relationRepository.findAll(specification, pageable);

        return Wrapper.success(new PageData<>(pageList.getTotalElements(), pageList.getContent().stream().map(p -> {
            MemberManageQueryVO queryVO = new MemberManageQueryVO();
            queryVO.setId(p.getId());
            //如果是渠道会员或有开启saas多租户部署，则取上级会员会员信息
            if (loginUser.getMemberLevelType().equals(MemberLevelTypeEnum.CHANNEL.getCode()) || isEnableMultiTenancy) {
                queryVO.setMemberId(p.getMemberId());
                queryVO.setName(p.getMember().getName());
                queryVO.setRoleId(p.getRoleId());
                queryVO.setRoleName(p.getRole().getRoleName());
                queryVO.setMemberTypeName(MemberTypeEnum.getCodeMessage(p.getRole().getMemberType().getTypeEnum()));
                queryVO.setLevel(p.getLevelRight().getLevel());
                queryVO.setLevelTag(p.getLevelRight().getLevelTag());
            } else {
                //取平台会员的下级会员信息
                queryVO.setMemberId(p.getSubMemberId());
                queryVO.setName(p.getSubMember().getName());
                queryVO.setRoleId(p.getSubRoleId());
                queryVO.setRoleName(p.getSubRoleName());
                queryVO.setMemberTypeName(MemberTypeEnum.getCodeMessage(p.getSubRole().getMemberType().getTypeEnum()));
                queryVO.setLevel(p.getLevelRight().getLevel());
                queryVO.setLevelTag(p.getLevelRight().getLevelTag());
            }
            return queryVO;
        }).collect(Collectors.toList())));
    }

    /**
     * 根据会员名称，分页查询角色为服务提供者的上级会员列表(增加条件会员等级类型为商户会员)
     * @param headers Http头部信息
     * @param pageByNameVO 接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<PageData<MemberManageQueryVO>> pageUpperProviderMerchantMember(HttpHeaders headers, MemberManagePageByNameVO pageByNameVO) {

        UserLoginCacheDTO loginUser = memberCacheService.needLoginFromBusinessPlatform(headers);

        Specification<MemberRelationDO> specification = (root, query, criteriaBuilder) -> {
            List<Predicate> list = new ArrayList<>();
            list.add(criteriaBuilder.equal(root.get("relType").as(Integer.class), MemberRelationTypeEnum.OTHER.getCode()));
            list.add(criteriaBuilder.equal(root.get("subMemberId").as(Long.class), loginUser.getMemberId()));
            list.add(criteriaBuilder.equal(root.get("subRoleId").as(Long.class), loginUser.getMemberRoleId()));
            list.add(criteriaBuilder.equal(root.get("verified").as(Integer.class), MemberValidateStatusEnum.VERIFY_PASSED.getCode()));
            list.add(criteriaBuilder.equal(root.get("status").as(Integer.class), MemberStatusEnum.NORMAL.getCode()));

            //上级会员角色为服务提供者且会员类型为企业会员或个人会员
            Join<Object, Object> roleJoin = root.join("role", JoinType.LEFT);
            list.add(criteriaBuilder.equal(roleJoin.get("roleType").get("typeEnum").as(Integer.class), RoleTypeEnum.SERVICE_PROVIDER.getCode()));
            list.add(criteriaBuilder.or(criteriaBuilder.equal(roleJoin.get("memberType").get("typeEnum").as(Integer.class), MemberTypeEnum.MERCHANT.getCode()), criteriaBuilder.equal(roleJoin.get("memberType").get("typeEnum").as(Integer.class), MemberTypeEnum.MERCHANT_PERSONAL.getCode())));

            // 上级会员名称
            if (StringUtils.hasLength(pageByNameVO.getName())) {
                Join<Object, Object> memberJoin = root.join("member", JoinType.LEFT);
                list.add(criteriaBuilder.like(memberJoin.get("name").as(String.class), "%" + pageByNameVO.getName().trim() + "%"));
            }

            Predicate[] p = new Predicate[list.size()];
            return criteriaBuilder.and(list.toArray(p));
        };

        Pageable page = PageRequest.of(pageByNameVO.getCurrent() - 1, pageByNameVO.getPageSize(), Sort.by("id").ascending());
        Page<MemberRelationDO> pageList = relationRepository.findAll(specification, page);
        return Wrapper.success(new PageData<>(pageList.getTotalElements(), pageList.getContent().stream().map(relationDO -> {
            MemberManageQueryVO queryVO = new MemberManageQueryVO();
            queryVO.setId(relationDO.getId());
            queryVO.setMemberId(relationDO.getMemberId());
            queryVO.setName(relationDO.getMember().getName());
            queryVO.setMemberTypeName(MemberTypeEnum.getCodeMessage(relationDO.getRole().getMemberType().getTypeEnum()));
            queryVO.setLevel(relationDO.getLevelRight().getLevel());
            queryVO.setLevelTag(relationDO.getLevelRight().getLevelTag());
            queryVO.setRoleId(relationDO.getRoleId());
            queryVO.setRoleName(relationDO.getRole().getRoleName());
            return queryVO;
        }).collect(Collectors.toList())));
    }

    /**
     * 根据会员名称，分页查询角色为服务消费者的上级会员列表(增加条件会员等级类型为商户会员)
     * @param headers Http头部信息
     * @param pageByNameVO 接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<PageData<MemberManageQueryVO>> pageUpperConsumerMerchantMember(HttpHeaders headers, MemberManagePageByNameVO pageByNameVO) {
        UserLoginCacheDTO loginUser = memberCacheService.needLoginFromBusinessPlatform(headers);

        Specification<MemberRelationDO> specification = (root, query, criteriaBuilder) -> {
            List<Predicate> list = new ArrayList<>();
            list.add(criteriaBuilder.equal(root.get("relType").as(Integer.class), MemberRelationTypeEnum.OTHER.getCode()));
            list.add(criteriaBuilder.equal(root.get("subMemberId").as(Long.class), loginUser.getMemberId()));
            list.add(criteriaBuilder.equal(root.get("subRoleId").as(Long.class), loginUser.getMemberRoleId()));
            list.add(criteriaBuilder.equal(root.get("verified").as(Integer.class), MemberValidateStatusEnum.VERIFY_PASSED.getCode()));
            list.add(criteriaBuilder.equal(root.get("status").as(Integer.class), MemberStatusEnum.NORMAL.getCode()));

            //上级会员角色为服务提供者
            Join<Object, Object> roleJoin = root.join("role", JoinType.LEFT);
            list.add(criteriaBuilder.equal(roleJoin.get("roleType").get("typeEnum").as(Integer.class), RoleTypeEnum.SERVICE_CONSUMER.getCode()));

            // 上级会员名称
            if (StringUtils.hasLength(pageByNameVO.getName())) {
                Join<Object, Object> memberJoin = root.join("member", JoinType.LEFT);
                list.add(criteriaBuilder.like(memberJoin.get("name").as(String.class), "%" + pageByNameVO.getName().trim() + "%"));
            }

            Predicate[] p = new Predicate[list.size()];
            return criteriaBuilder.and(list.toArray(p));
        };

        Pageable page = PageRequest.of(pageByNameVO.getCurrent() - 1, pageByNameVO.getPageSize(), Sort.by("id").ascending());
        Page<MemberRelationDO> pageList = relationRepository.findAll(specification, page);
        return Wrapper.success(new PageData<>(pageList.getTotalElements(), pageList.getContent().stream().map(relationDO -> {
            MemberManageQueryVO queryVO = new MemberManageQueryVO();
            queryVO.setId(relationDO.getId());
            queryVO.setMemberId(relationDO.getMemberId());
            queryVO.setName(relationDO.getMember().getName());
            queryVO.setMemberTypeName(MemberTypeEnum.getCodeMessage(relationDO.getRole().getMemberType().getTypeEnum()));
            queryVO.setLevel(relationDO.getLevelRight().getLevel());
            queryVO.setLevelTag(relationDO.getLevelRight().getLevelTag());
            queryVO.setRoleId(relationDO.getRoleId());
            queryVO.setRoleName(relationDO.getRole().getRoleName());
            return queryVO;
        }).collect(Collectors.toList())));
    }

    /**
     * 根据会员名称，分页查询角色为当前会员所属的下属会员且角色类型为服务提供的会员
     * @param headers Http头部信息
     * @param pageByNameVO 接口参数
     * @return 查询结果
     */
    @Override
    public Wrapper<PageData<MemberManageQueryVO>> pageLowerProviderMerchantMember(HttpHeaders headers, MemberManagePageByNameVO pageByNameVO) {
        UserLoginCacheDTO loginUser = memberCacheService.needLoginFromBusinessPlatform(headers);
        Specification<MemberRelationDO> specification = (root, query, criteriaBuilder) -> {
            List<Predicate> list = new ArrayList<>();
            list.add(criteriaBuilder.equal(root.get("relType").as(Integer.class), MemberRelationTypeEnum.OTHER.getCode()));
            list.add(criteriaBuilder.equal(root.get("memberId").as(Long.class), loginUser.getMemberId()));
            list.add(criteriaBuilder.equal(root.get("roleId").as(Long.class), loginUser.getMemberRoleId()));
            list.add(criteriaBuilder.equal(root.get("verified").as(Integer.class), MemberValidateStatusEnum.VERIFY_PASSED.getCode()));
            list.add(criteriaBuilder.equal(root.get("status").as(Integer.class), MemberStatusEnum.NORMAL.getCode()));

            //下级会员角色为服务提供者
            Join<Object, Object> roleJoin = root.join("role", JoinType.LEFT);
            list.add(criteriaBuilder.equal(roleJoin.get("roleType").get("typeEnum").as(Integer.class), RoleTypeEnum.SERVICE_PROVIDER.getCode()));

            // 下级会员名称
            if (StringUtils.hasLength(pageByNameVO.getName())) {
                Join<Object, Object> memberJoin = root.join("subMember", JoinType.LEFT);
                list.add(criteriaBuilder.like(memberJoin.get("name").as(String.class), "%" + pageByNameVO.getName().trim() + "%"));
            }

            Predicate[] p = new Predicate[list.size()];
            return criteriaBuilder.and(list.toArray(p));
        };
        Pageable page = PageRequest.of(pageByNameVO.getCurrent() - 1, pageByNameVO.getPageSize(), Sort.by("id").ascending());
        Page<MemberRelationDO> pageList = relationRepository.findAll(specification, page);
        return Wrapper.success(new PageData<>(pageList.getTotalElements(), pageList.getContent().stream().map(relationDO -> {
            MemberManageQueryVO queryVO = new MemberManageQueryVO();
            queryVO.setId(relationDO.getId());
            queryVO.setMemberId(relationDO.getMemberId());
            queryVO.setName(relationDO.getMember().getName());
            queryVO.setMemberTypeName(MemberTypeEnum.getCodeMessage(relationDO.getRole().getMemberType().getTypeEnum()));
            queryVO.setLevel(relationDO.getLevelRight().getLevel());
            queryVO.setLevelTag(relationDO.getLevelRight().getLevelTag());
            queryVO.setRoleId(relationDO.getRoleId());
            queryVO.setRoleName(relationDO.getRole().getRoleName());
            return queryVO;
        }).collect(Collectors.toList())));
    }

    /**
     * “选择采购会员”功能
     *
     * @param headers Http头部信息
     * @param nameVO  接口参数
     * @return 新增结果
     */
    @Override
    public Wrapper<PageData<MemberManageQueryVO>> buyerMemberInfo(HttpHeaders headers, MemberNameVO nameVO) {
        UserLoginCacheDTO loginUser = memberCacheService.needLoginFromBusinessPlatform(headers);

        //如果当前登录会员角色类型不是服务消费者
        if (!loginUser.getMemberRoleType().equals(RoleTypeEnum.SERVICE_PROVIDER.getCode())) {
            return Wrapper.success(new PageData<>(0L, new ArrayList<>()));
        }

        // step 1:调用查询站点是否有勾选【SAAS多租户部署】
        Boolean isEnableMultiTenancy = siteService.isEnableMultiTenancy(headers).getData();

        Specification<MemberRelationDO> specification;

        //如果会员类型是企业会员或个人会员且会员角色类型是服务消费且【PAAS-站点管理】有勾选【SAAS多租户部署】
        //企业会员或个人会员这个条件等价于会员等级类型为商户会员
        if (loginUser.getMemberLevelType().equals(MemberLevelTypeEnum.MERCHANT.getCode()) && isEnableMultiTenancy) {
            specification = (root, query, criteriaBuilder) -> {
                List<Predicate> list = new ArrayList<>();
                list.add(criteriaBuilder.equal(root.get("relType").as(Integer.class), MemberRelationTypeEnum.OTHER.getCode()));
                list.add(criteriaBuilder.equal(root.get("memberId").as(Long.class), loginUser.getMemberId()));
                list.add(criteriaBuilder.equal(root.get("roleId").as(Long.class), loginUser.getMemberRoleId()));
                list.add(criteriaBuilder.equal(root.get("verified").as(Integer.class), MemberValidateStatusEnum.VERIFY_PASSED.getCode()));
                list.add(criteriaBuilder.equal(root.get("status").as(Integer.class), MemberStatusEnum.NORMAL.getCode()));

                //下级会员角色为服务消费者且会员类型为企业会员或个人会员
                Join<Object, Object> roleJoin = root.join("subRole", JoinType.LEFT);
                list.add(criteriaBuilder.equal(roleJoin.get("roleType").get("typeEnum").as(Integer.class), RoleTypeEnum.SERVICE_CONSUMER.getCode()));
                list.add(criteriaBuilder.or(criteriaBuilder.equal(roleJoin.get("memberType").get("typeEnum").as(Integer.class), MemberTypeEnum.MERCHANT.getCode()), criteriaBuilder.equal(roleJoin.get("memberType").get("typeEnum").as(Integer.class), MemberTypeEnum.MERCHANT_PERSONAL.getCode())));

                // 下级会员名称
                if (StringUtils.hasLength(nameVO.getMemberName())) {
                    Join<Object, Object> memberJoin = root.join("subMember", JoinType.LEFT);
                    list.add(criteriaBuilder.like(memberJoin.get("name").as(String.class), "%" + nameVO.getMemberName().trim() + "%"));
                }

                Predicate[] p = new Predicate[list.size()];
                return criteriaBuilder.and(list.toArray(p));
            };
        } else {
            //当前会员的会员类型是企业会员或个人会员且会员角色类型是服务提供时，会员数据来源于【平台后台--会员管理--会员维护】中会员类型为企业会员或个人会员且会员角色类型为服务消费的会员数据
            //当前会员的会员类型是渠道企业会员或渠道个人会员且会员角色类型是服务提供时，会员数据来源于【会员能力--会员管理--会员信息】中当前渠道会员的下级渠道会员且会员类型为渠道企业会员或渠道个人会员且会员角色类型为服务消费
            specification = (root, query, criteriaBuilder) -> {
                List<Predicate> list = new ArrayList<>();
                if (loginUser.getMemberLevelType().equals(MemberLevelTypeEnum.MERCHANT.getCode())) {
                    list.add(criteriaBuilder.equal(root.get("relType").as(Integer.class), MemberRelationTypeEnum.PLATFORM.getCode()));
                    list.add(criteriaBuilder.equal(root.get("subRole").get("roleType").get("typeEnum").as(Integer.class), RoleTypeEnum.SERVICE_CONSUMER.getCode()));
                    list.add(criteriaBuilder.or(criteriaBuilder.equal(root.get("subRole").get("memberType").get("typeEnum").as(Integer.class), MemberTypeEnum.MERCHANT.getCode()), criteriaBuilder.equal(root.get("subRole").get("memberType").get("typeEnum").as(Integer.class), MemberTypeEnum.MERCHANT_PERSONAL.getCode())));

                    if (StringUtils.hasText(nameVO.getMemberName())) {
                        list.add(criteriaBuilder.like(root.get("subMember").get("name").as(String.class), "%" + nameVO.getMemberName().trim() + "%"));
                    }
                }

                if (loginUser.getMemberLevelType().equals(MemberLevelTypeEnum.CHANNEL.getCode())) {
                    list.add(criteriaBuilder.equal(root.get("memberId").as(Long.class), loginUser.getMemberId()));
                    list.add(criteriaBuilder.equal(root.get("roleId").as(Long.class), loginUser.getMemberRoleId()));
                    list.add(criteriaBuilder.equal(root.get("relType").as(Integer.class), MemberRelationTypeEnum.OTHER.getCode()));
                    list.add(criteriaBuilder.or(criteriaBuilder.equal(root.get("subRole").get("memberType").get("typeEnum").as(Integer.class), MemberTypeEnum.CHANNEL.getCode()), criteriaBuilder.equal(root.get("role").get("memberType").get("typeEnum").as(Integer.class), MemberTypeEnum.CHANNEL_PERSONAL.getCode())));
                    list.add(criteriaBuilder.equal(root.get("subRole").get("roleType").get("typeEnum").as(Integer.class), RoleTypeEnum.SERVICE_CONSUMER.getCode()));

                    if (StringUtils.hasText(nameVO.getMemberName())) {
                        list.add(criteriaBuilder.like(root.get("subMember").get("name").as(String.class), "%" + nameVO.getMemberName().trim() + "%"));
                    }
                }
                Predicate[] p = new Predicate[list.size()];
                return criteriaBuilder.and(list.toArray(p));
            };
        }

        Pageable pageable = PageRequest.of(nameVO.getCurrent() - 1, nameVO.getPageSize(), Sort.by("id").descending());
        Page<MemberRelationDO> pageList = relationRepository.findAll(specification, pageable);

        return Wrapper.success(new PageData<>(pageList.getTotalElements(), pageList.getContent().stream().map(p -> {
            MemberManageQueryVO queryVO = new MemberManageQueryVO();
            queryVO.setId(p.getId());
            queryVO.setMemberId(p.getSubMemberId());
            queryVO.setName(p.getSubMember().getName());
            queryVO.setRoleId(p.getSubRoleId());
            queryVO.setRoleName(p.getSubRoleName());
            queryVO.setMemberTypeName(MemberTypeEnum.getCodeMessage(p.getSubRole().getMemberType().getTypeEnum()));
            queryVO.setLevel(p.getLevelRight().getLevel());
            queryVO.setLevelTag(p.getLevelRight().getLevelTag());
            return queryVO;
        }).collect(Collectors.toList())));
    }

    /**
     * “选择供应会员”功能
     *
     * @param headers Http头部信息
     * @param nameVO  接口参数
     * @return 新增结果
     */
    @Override
    public Wrapper<PageData<MemberManageQueryVO>> supplyMemberInfo(HttpHeaders headers, MemberNameVO nameVO) {
        UserLoginCacheDTO loginUser = memberCacheService.needLoginFromBusinessPlatform(headers);

        //如果当前登录会员角色类型不是服务消费者
        if (!loginUser.getMemberRoleType().equals(RoleTypeEnum.SERVICE_CONSUMER.getCode())) {
            return Wrapper.success(new PageData<>(0L, new ArrayList<>()));
        }

        // step 1:调用查询站点是否有勾选【SAAS多租户部署】
        Boolean isEnableMultiTenancy = siteService.isEnableMultiTenancy(headers).getData();

        Specification<MemberRelationDO> specification;

        //如果会员类型是企业会员或个人会员且会员角色类型是服务消费且【PAAS-站点管理】有勾选【SAAS多租户部署】
        //企业会员或个人会员这个条件等价于会员等级类型为商户会员
        if (loginUser.getMemberLevelType().equals(MemberLevelTypeEnum.MERCHANT.getCode()) && isEnableMultiTenancy) {
            specification = (root, query, criteriaBuilder) -> {
                List<Predicate> list = new ArrayList<>();
                list.add(criteriaBuilder.equal(root.get("relType").as(Integer.class), MemberRelationTypeEnum.OTHER.getCode()));
                list.add(criteriaBuilder.equal(root.get("subMemberId").as(Long.class), loginUser.getMemberId()));
                list.add(criteriaBuilder.equal(root.get("subRoleId").as(Long.class), loginUser.getMemberRoleId()));
                list.add(criteriaBuilder.equal(root.get("verified").as(Integer.class), MemberValidateStatusEnum.VERIFY_PASSED.getCode()));
                list.add(criteriaBuilder.equal(root.get("status").as(Integer.class), MemberStatusEnum.NORMAL.getCode()));

                //上级会员角色为服务提供者且会员类型为企业会员或个人会员
                Join<Object, Object> roleJoin = root.join("role", JoinType.LEFT);
                list.add(criteriaBuilder.equal(roleJoin.get("roleType").get("typeEnum").as(Integer.class), RoleTypeEnum.SERVICE_PROVIDER.getCode()));
                list.add(criteriaBuilder.or(criteriaBuilder.equal(roleJoin.get("memberType").get("typeEnum").as(Integer.class), MemberTypeEnum.MERCHANT.getCode()), criteriaBuilder.equal(roleJoin.get("memberType").get("typeEnum").as(Integer.class), MemberTypeEnum.MERCHANT_PERSONAL.getCode())));

                // 上级会员名称
                if (StringUtils.hasLength(nameVO.getMemberName())) {
                    Join<Object, Object> memberJoin = root.join("member", JoinType.LEFT);
                    list.add(criteriaBuilder.like(memberJoin.get("name").as(String.class), "%" + nameVO.getMemberName().trim() + "%"));
                }

                Predicate[] p = new Predicate[list.size()];
                return criteriaBuilder.and(list.toArray(p));
            };
        } else {
            //当前会员的会员类型是企业会员或个人会员且会员角色类型是服务消费时，会员数据来源于【平台后台--会员管理--会员维护】中会员类型为企业会员或个人会员且会员角色类型为服务提供的会员数据
            //当前会员的会员类型是渠道企业会员或渠道个人会员且会员角色类型是服务消费时，会员数据来源于会员能力--会员信息查询中当前渠道会员的上级渠道会员且会员等级类型为渠道会员且会员角色类型为服务提供
            specification = (root, query, criteriaBuilder) -> {
                List<Predicate> list = new ArrayList<>();
                if (loginUser.getMemberLevelType().equals(MemberLevelTypeEnum.MERCHANT.getCode())) {
                    list.add(criteriaBuilder.equal(root.get("relType").as(Integer.class), MemberRelationTypeEnum.PLATFORM.getCode()));
                    list.add(criteriaBuilder.equal(root.get("subRole").get("roleType").get("typeEnum").as(Integer.class), RoleTypeEnum.SERVICE_PROVIDER.getCode()));
                    list.add(criteriaBuilder.or(criteriaBuilder.equal(root.get("subRole").get("memberType").get("typeEnum").as(Integer.class), MemberTypeEnum.MERCHANT.getCode()), criteriaBuilder.equal(root.get("subRole").get("memberType").get("typeEnum").as(Integer.class), MemberTypeEnum.MERCHANT_PERSONAL.getCode())));

                    if (StringUtils.hasText(nameVO.getMemberName())) {
                        list.add(criteriaBuilder.like(root.get("subMember").get("name").as(String.class), "%" + nameVO.getMemberName().trim() + "%"));
                    }
                }

                if (loginUser.getMemberLevelType().equals(MemberLevelTypeEnum.CHANNEL.getCode())) {
                    list.add(criteriaBuilder.equal(root.get("subMemberId").as(Long.class), loginUser.getMemberId()));
                    list.add(criteriaBuilder.equal(root.get("subRoleId").as(Long.class), loginUser.getMemberRoleId()));
                    list.add(criteriaBuilder.equal(root.get("relType").as(Integer.class), MemberRelationTypeEnum.OTHER.getCode()));
                    list.add(criteriaBuilder.or(criteriaBuilder.equal(root.get("role").get("memberType").get("typeEnum").as(Integer.class), MemberTypeEnum.CHANNEL.getCode()), criteriaBuilder.equal(root.get("role").get("memberType").get("typeEnum").as(Integer.class), MemberTypeEnum.CHANNEL_PERSONAL.getCode())));
                    list.add(criteriaBuilder.equal(root.get("role").get("roleType").get("typeEnum").as(Integer.class),RoleTypeEnum.SERVICE_PROVIDER.getCode()));

                    if (StringUtils.hasText(nameVO.getMemberName())) {
                        list.add(criteriaBuilder.like(root.get("member").get("name").as(String.class), "%" + nameVO.getMemberName().trim() + "%"));
                    }
                }
                Predicate[] p = new Predicate[list.size()];
                return criteriaBuilder.and(list.toArray(p));
            };
        }

        Pageable pageable = PageRequest.of(nameVO.getCurrent() - 1, nameVO.getPageSize(), Sort.by("id").descending());
        Page<MemberRelationDO> pageList = relationRepository.findAll(specification, pageable);

        return Wrapper.success(new PageData<>(pageList.getTotalElements(), pageList.getContent().stream().map(p -> {
            MemberManageQueryVO queryVO = new MemberManageQueryVO();
            queryVO.setId(p.getId());
            //如果是渠道会员或有开启saas多租户部署，则取上级会员会员信息
            if (loginUser.getMemberLevelType().equals(MemberLevelTypeEnum.CHANNEL.getCode()) || isEnableMultiTenancy) {
                queryVO.setMemberId(p.getMemberId());
                queryVO.setName(p.getMember().getName());
                queryVO.setRoleId(p.getRoleId());
                queryVO.setRoleName(p.getRole().getRoleName());
                queryVO.setMemberTypeName(MemberTypeEnum.getCodeMessage(p.getRole().getMemberType().getTypeEnum()));
                queryVO.setLevel(p.getLevelRight().getLevel());
                queryVO.setLevelTag(p.getLevelRight().getLevelTag());
            } else {
                //取平台会员的下级会员信息
                queryVO.setMemberId(p.getSubMemberId());
                queryVO.setName(p.getSubMember().getName());
                queryVO.setRoleId(p.getSubRoleId());
                queryVO.setRoleName(p.getSubRoleName());
                queryVO.setMemberTypeName(MemberTypeEnum.getCodeMessage(p.getSubRole().getMemberType().getTypeEnum()));
                queryVO.setLevel(p.getLevelRight().getLevel());
                queryVO.setLevelTag(p.getLevelRight().getLevelTag());
            }
            return queryVO;
        }).collect(Collectors.toList())));
    }
}
